Objective C一些NSString不转向NSCFString

时间:2011-01-13 08:26:41

标签: objective-c xcode nsstring

您好我已经声明并初始化了3个变量NSString

static NSString* accidtest;
static NSString* accnumber;  
static NSString* accprefix;

稍后在程序中

[[accidtest initWithString:@"0293749372920383"]freeWhenDone:NO]; 
[[accnumber alloc] init];
[[accprefix alloc] init];

我从xml给了他们一个值 像那样

accnumber = string;
accprefix = string;

但最后当我想使用它们时,我发现问题只是转为NSCFString并保存其他值超出范围。

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

这更正确:

/* these initialize to nil */
static NSString* accidtest;
static NSString* accnumber;
static NSString* accprefix;

/* ... */

/* ??? freeWhenDone */
assert(nil == accidtest); /* make sure we aren't creating twice, leaking the previous assignment */
accidtest = [[NSString alloc] initWithString:@"0293749372920383"];

assert(nil == accnumber); /* make sure we aren't creating twice, leaking the previous assignment */
accnumber = [[NSString alloc] initWithString:string];

assert(nil == accprefix); /* make sure we aren't creating twice, leaking the previous assignment */
accprefix = [[NSString alloc] initWithString:string];

答案 1 :(得分:1)

您尝试在非初始化变量上调用-alloc。这没有任何意义,编译器应该为此大吼大叫。相反,你应该有像

这样的东西
accidtest = [[NSString alloc] initWithString:@"0293749372920383"];
accnumber = [[NSString alloc] init]; // what's the point of this? Equivalent to @""