紧接着自动释放的保留有什么意义?

发布于 2024-09-27 11:20:20 字数 479 浏览 6 评论 0原文

我正在查看一些开源代码,并试图理解为什么作者以特定的方式做了某些事情。

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

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

发布评论

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

评论(1

瑾兮 2024-10-04 11:20:20

让我们假设 top 看起来像这样:

- (id) top {
    return [stack lastObject];
}

然后想象一下:

foo = [bar top];
[bar removeAllObjects];
// Do something with foo

会发生以下情况:第二行将使保留计数下降到 0,到第三行 foo 将指向已释放的内存。但使用 retainautorelease 时,保留计数为 1,直到池清空,因此在第三行 foo 仍将指向有效的目的。

Let's assume top would look like this:

- (id) top {
    return [stack lastObject];
}

Then imagine this:

foo = [bar top];
[bar removeAllObjects];
// Do something with foo

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 the retain and autorelease the retain count is 1, until the pool is emptied thus on the third line foo would still point to a valid object.

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