将字符串附加到 NSMutableString

发布于 2024-08-27 11:52:28 字数 473 浏览 6 评论 0原文

现在已经研究了一会儿,但不明白为什么这段简单的代码会抛出错误。为简洁起见缩短:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自由范儿 2024-09-03 11:52:28

行更改

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.

走过海棠暮 2024-09-03 11:52:28

事实上,解决方案确实与保留有关,正如用户不变所指出的那样。类方法:

output = [NSMutableString stringWithCapacity:0];

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

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

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

编辑

找出原因。我直接访问实例变量,而不是通过我合成的 getter/setter。有关更多信息,请访问我的博客

The solution did in fact have to do with retention, as indicated by user invariant. The class method:

output = [NSMutableString stringWithCapacity:0];

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:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文