首页 > NSString 作为参数传到另外个类的函数里报错

NSString 作为参数传到另外个类的函数里报错

ValueObject

#import <Foundation/Foundation.h>

@interface CurrentDataVO : NSObject

@property (nonatomic, retain) NSString *crt;
@property (nonatomic, retain) NSString *last;
@property (nonatomic, retain) NSString *dataType;
@property (nonatomic, retain) NSString *date;
@property (nonatomic, retain) NSMutableArray *days;
@property (nonatomic, retain) NSString *cv;

- (void)showAllData;

#import "CurrentDataVO.h"

@implementation CurrentDataVO

@synthesize crt;
@synthesize last;
@synthesize dataType;
@synthesize date;
@synthesize days;
@synthesize cv;

- (id)init
{
    self = [super init];
    if (self) {
        days = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)showAllData
{
    NSLog(@"%@", crt);
    NSLog(@"%@", last);
    NSLog(@"%@", dataType);
    NSLog(@"%@", date);
    NSLog(@"%@", cv);
    NSLog(@"%@", days);
}

@end

ViewCtrlA

[cell setContentData:todayData withYesData:vo.last];

ViewCtrlB

- (void)setContentData:(NSString *)todayData withYesData:(NSString *)yesData
{
    [todayDataLabel setText:todayData];
    [yesDataLabel setText:yesData];
}

cell不为nil
在ViewCtrlB中 NSlog 能打印出 todayData,但是赋值到setText中时会抛出异常。

2012-12-13 14:10:35.510 mbaforios[29723:fb03] 1005
2012-12-13 14:10:35.511 mbaforios[29723:fb03] -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x6b904e0
2012-12-13 14:10:35.511 mbaforios[29723:fb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x6b904e0'
*** First throw call stack:
(0x12f1022 0x17a2cd6 0x12f2cbd 0x1257ed0 0x1257cb2 0x46a0ff 0x7abd 0x440c 0x93d9 0xd2da49 0xd2be84 0xd2cea7 0xd2be3f 0xd2bfc5 0xc70f5a 0x1a52a39 0x1b1f596 0x1b1f861 0x1a49120 0x1b1f117 0x1a48fbf 0x12c594f 0x1228b43 0x1228424 0x1227d84 0x1227c9b 0x1fab7d8 0x1fab88a 0x32a626 0x2ad2 0x2a45)
terminate called throwing an exception(lldb)

我猜是你服务端过来的时候把NSNumber对象认为了NSString对象,然后你打印NSNumber是对的,但是给Label赋值的时候就报错了,因为它不是NSString而是NSNumber,跟copy不copy,释放不是释放没有关系。只是类型错了。


楼上gaosboy正解,我只是做个补充,
因为NSString字符串是autorelease的,在多层方法传递赋值时会在中间某一层传递中释放掉。

分割线

我说NSString是autorelease这个是错误的,NSString *str = @"123",这样得到的字符串是字符串常量,并非autorelease。
这个是不对的,本意是表达在参数传递过程中NSString *str = obj;这样得到的str是autorelease的。

题外话:
immutable value 尽量使用copy属性


确实是在初始化NSString赋值的时候,格式有问题,导致这个NSString 不合法。 谢谢大家。


首先VCA中的那个cell是VCB的实例吗?
如果是的话,看样子是VCA中todayData出了问题,是赋值进去以后被释放了。
你可以在VCA中打一个断点,看看todayData的状态,是否是一个完整的NSString对象,如果真的是这个问题,修改VCA的代码:

[cell setContentData:[todayData retain] withYesData:vo.last];

NSString 是不是这样的 @property (nonatomic, assign) 改为@property (nonatomic, strong)

【热门文章】
【热门文章】