将字符串附加到 NSMutableString
现在已经研究了一会儿,但不明白为什么这段简单的代码会抛出错误。为简洁起见缩短:
NSMutableString *output;
...
@property (nonatomic, retain) NSMutableString *output;
...
@synthesize output;
...
// logs "output start" as expected
output = [NSMutableString stringWithCapacity:0];
[output appendString:@"output start"];
NSLog(@"%@", output);
...
// error happens here
// this is later on in a different method
[output appendString:@"doing roll for player"];
有人能发现我的错误吗?
Been looking at this for a bit now and not understanding why this simple bit of code is throwing an error. Shortened for brevity:
NSMutableString *output;
...
@property (nonatomic, retain) NSMutableString *output;
...
@synthesize output;
...
// logs "output start" as expected
output = [NSMutableString stringWithCapacity:0];
[output appendString:@"output start"];
NSLog(@"%@", output);
...
// error happens here
// this is later on in a different method
[output appendString:@"doing roll for player"];
Can anyone spot my mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
行更改
将
output = [NSMutableString stringWithString:@"output start"]
为
[self setOutput:[NSMutableString stringWithString:@"output start"]]
(或
self.output = ...
(如果您喜欢这种表示法)。尽管您已经声明了一个属性,但您没有使用 setter,因此您没有保留该字符串。
Change the line
output = [NSMutableString stringWithString:@"output start"]
to
[self setOutput:[NSMutableString stringWithString:@"output start"]]
(or
self.output = ...
if you prefer that notation).Although you have declared a property, you are not using the setter, so you are not retaining the string.
事实上,解决方案确实与保留有关,正如用户不变所指出的那样。类方法:
返回一个
autorelease
NSMutableString。当分配给我的输出属性时——看起来,即使有保留标志——它也没有保留它。解决方案是自己分配它而不是自动释放:然后保留就起作用了。任何关于原因的解释都将非常受欢迎。
编辑
找出原因。我直接访问实例变量,而不是通过我合成的 getter/setter。有关更多信息,请访问我的博客。
The solution did in fact have to do with retention, as indicated by user invariant. The class method:
returns an
autorelease
NSMutableString. When assigned to my output property -- seemingly, even with the retain flag -- it did not retain it. The solution was to alloc it myself and not autorelease:Then the retain worked. Any explanation as to why would be very welcome.
Edit
Figured out why. I was accessing the instance vars directly instead of through the getter/setter that I synthesized. More info on my blog.