从自动释放对象上的保留转变的引用是否需要释放?

发布于 2024-12-20 13:54:37 字数 348 浏览 6 评论 0原文

对于以下代码,1 - 从 getFoo 返回的对象上需要保留; 2 - 方法 func 中的 foo 是否需要释放?

- (NSString *)getFoo {
    return [[[NSString alloc] initWithString:@"foo"] autorelease];
}

- (void)func {
    // ??? is the retain needed?
    NSString *foo = [[self getFoo] retain];

    // use foo

    // ??? is the release needed?
    [foo release];
}

For the following code, 1 - is retain needed on the object returned back from getFoo; 2 - is the release needed on foo in method func?

- (NSString *)getFoo {
    return [[[NSString alloc] initWithString:@"foo"] autorelease];
}

- (void)func {
    // ??? is the retain needed?
    NSString *foo = [[self getFoo] retain];

    // use foo

    // ??? is the release needed?
    [foo release];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

美人迟暮 2024-12-27 13:54:37

每个retain 必须与release 匹配。

这就是说,在你的 func 中,如果你不延迟它的使用,你就不需要 retain *foo 。
通常,自动释放池会在运行循环结束时获取drain,以便您有时间在函数中本地使用它。
但如果您保留,则必须释放

你可以这样做:

return [NSString stringWithString:@"foo];

这是一个方便的方法,它返回一个 autorelease 对象给你。

Every retain must be match with a release.

This said, in your func you don't need to retain *foo if you are not delaying it's use.
Usually autorelease pool get's drain at the end of the run loop so you have the time to use it locally in your function.
But if you retain you must release.

And you could do this :

return [NSString stringWithString:@"foo];

This is a convenience methode that return an autorelease object to you.

┈┾☆殇 2024-12-27 13:54:37

如果您分配复制保留一个对象,您需要释放它。

在您的示例中,您不需要保留它。但既然你这样做了,你确实需要释放它。

If you alloc, copy or retain an object you need to release it.

In your example, you don't need to retain it. But since you did, you do need to release it.

梦境 2024-12-27 13:54:37

你写的代码没问题。
当您分配字符串时,它的保留计数为 1。
然后,您自动释放该字符串,这将在稍后减少保留计数。
你用foo.
那么你不需要释放它,因为你已经自动释放了它:它稍后会自动释放。

请注意,您可以使用 stringWithFormat 或 stringWithString 创建已自动释放的字符串。

这会更整洁一点。

The code you've written is fine.
When you alloc the string it's retain count is 1.
You then autorelease the string which will decrement the retain count at a later time.
You use foo.
Then you don't need to release it since you already autoreleased it: it will automatically be released later.

Note that you could use stringWithFormat or stringWithString to create a string that is already autoreleased.

This would be a bit neater.

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