初始化 NSString 时将 alloc 和 init 分开
我有一种情况,我想分配一个 NSString 对象,并在 if-else 块内为其分配文本。当我编写这样的代码时:
NSString *string = [NSString alloc];
if (firstCase)
[string initWithString:@"firstCase"];
else if(secondCase)
[string initWithString:@"secondCase"];
[self someFunction:string];
我在 someFunction
内部收到错误(当我尝试使用 string
时抛出 NSInvalidArgumentException)。 另外,当我单步执行代码时,一旦输入 someFunction
,控制台就会生成一行内容:
你忘记嵌套alloc和init了吗?
它指的是字符串
。
我已经尝试使用 NSMutableString 进行同样的操作,只是执行 string = [[NSMutableString alloc] init]
并附加到每个 if-else 块中的字符串,但我想知道是否有人知道为什么以前的方法不会产生相同的结果。
I have a situation where I want to allocate a single NSString object, and assign text to it inside of an if-else block. When I write the code like this:
NSString *string = [NSString alloc];
if (firstCase)
[string initWithString:@"firstCase"];
else if(secondCase)
[string initWithString:@"secondCase"];
[self someFunction:string];
I get an error inside of someFunction
(throws an NSInvalidArgumentException when I try to use string
).
Also, when I step through my code, once i enter someFunction
, the console produces a line that says:
Did you forget to nest alloc and init?
which is referring to string
.
I've tried the same thing using an NSMutableString and just doing string = [[NSMutableString alloc] init]
and just appending to the string in each if-else block, but I was wondering if anyone knew why the previous way does not produce the same results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否可能遇到不满足 if 和 else if 要求的情况?您可能需要仔细检查您的情况...或者您可能希望将字符串默认为“”。 编辑:在使用 stringByAppendingString 将字符串声明为某个值后,您可以将其追加到该字符串
这里是苹果 NSString 类参考的链接:
http://开发人员。 apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
Is it possible your running into a case where you are not meeting requirements for your if and else if?? you might want to double check what your cases are... or you might want to default your string to "". EDIT: you can then append to the string after you have declared it to some value using stringByAppendingString
here is a link to apple's NSString class reference:
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html