从自动释放对象上的保留转变的引用是否需要释放?
对于以下代码,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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每个
retain
必须与release
匹配。这就是说,在你的 func 中,如果你不延迟它的使用,你就不需要
retain
*foo 。通常,自动释放池会在运行循环结束时获取
drain
,以便您有时间在函数中本地使用它。但如果您
保留
,则必须释放
。你可以这样做:
这是一个方便的方法,它返回一个
autorelease
对象给你。Every
retain
must be match with arelease
.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 mustrelease
.And you could do this :
This is a convenience methode that return an
autorelease
object to you.如果您
分配
、复制
或保留
一个对象,您需要释放
它。在您的示例中,您不需要保留它。但既然你这样做了,你确实需要释放它。
If you
alloc
,copy
orretain
an object you need torelease
it.In your example, you don't need to retain it. But since you did, you do need to release it.
你写的代码没问题。
当您分配字符串时,它的保留计数为 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.