紧接着自动释放的保留有什么意义?
我正在查看一些开源代码,并试图理解为什么作者以特定的方式做了某些事情。
该类是 NSArray
的包装器,用于创建具有推送、弹出等功能的堆栈数据结构。
其中一个方法是 topObject
,它返回堆栈上最顶层的对象,其实现是:
- (id)top {
return [[[stack lastObject] retain] autorelease]; // stack is an instance of NSMutableArray
}
保留后立即自动释放是怎么回事?
我最初的反应是,这将阻止分析器发出有关内存泄漏的警告,但我在没有保留/自动释放的情况下进行了分析,并且仍然没有警告。
从生命周期来看,一个对象会被创建,推入堆栈并释放,因此堆栈拥有该对象(底层数组将在添加时保留它)。
所以我不明白这里保留/自动释放的用途......
I'm looking at some open source code and trying to understand why the author has done something in a particular way.
The class is a wrapper around NSArray
to create a stack data structure with push, pop, etc.
One method is topObject
which returns the topmost object on the stack and its implementation is:
- (id)top {
return [[[stack lastObject] retain] autorelease]; // stack is an instance of NSMutableArray
}
What's with the retain followed by an immediate autorelease?
My initial reaction was that this would prevent an analyser warning about a memory leak, but I analysed without the retain/autorelease and there was still no warning.
Looking at the lifecycle, an object would be created, pushed to the stack and released, so the stack owns the object (the underlying array will retain it upon adding).
So I don't understand the use of the retain/autorelease here...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我们假设
top
看起来像这样:然后想象一下:
会发生以下情况:第二行将使保留计数下降到 0,到第三行
foo
将指向已释放的内存。但使用retain
和autorelease
时,保留计数为 1,直到池清空,因此在第三行foo
仍将指向有效的目的。Let's assume
top
would look like this:Then imagine this:
The following would happen: The second line would make the retain count drop to 0, and by the third line
foo
would point to deallocated memory. But with theretain
andautorelease
the retain count is 1, until the pool is emptied thus on the third linefoo
would still point to a valid object.