6

现在一直在看这个,不明白为什么这个简单的代码会引发错误。为简洁起见缩短:

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"];

谁能发现我的错误?

4

2 回答 2

2

换行

output = [NSMutableString stringWithString:@"output start"]

[self setOutput:[NSMutableString stringWithString:@"output start"]]

(或者self.output = ...如果您更喜欢这种表示法)。

尽管您已经声明了一个属性,但您没有使用 setter,因此您没有保留字符串。

于 2010-04-01T07:34:26.223 回答
1

正如 user invariant所指出的那样,该解决方案实际上确实与保留有关。类方法:

output = [NSMutableString stringWithCapacity:0];

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

output = [[NSMutableString alloc] initWithCapacity:0];

然后保留工作。任何解释为什么都会非常受欢迎。

编辑

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

于 2010-04-01T18:40:18.287 回答