将字符串附加到NSMutableString

typ*_*ror 6 objective-c 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"];
Run Code Online (Sandbox Code Playgroud)

谁能发现我的错误?

typ*_*ror 1

正如用户不变式所示,该解决方案实际上与保留有关。类方法:

output = [NSMutableString stringWithCapacity:0];
Run Code Online (Sandbox Code Playgroud)

返回一个autoreleaseNSMutableString。当分配给我的输出属性时——看起来,即使有保留标志——它也没有保留它。解决方案是我自己分配它而不是自动释放:

output = [[NSMutableString alloc] initWithCapacity:0];
Run Code Online (Sandbox Code Playgroud)

然后保留就起作用了。任何关于原因的解释都将非常受欢迎。

编辑

明白为什么了。我直接访问实例变量,而不是通过我合成的 getter/setter。更多信息请参见我的博客