objective-c - Objective-C 中的自动释放池 - 释放主自动释放池?

标签 objective-c ios memory-management autorelease nsautoreleasepool

据我了解,当向对象发送 autorelease 消息时,如果除了 main.m 中的自动释放池之外不存在自动释放池,则该对象将被放置在一个在 main.m 中。假设这是正确的,我有几个问题:

1) 是否所有自动释放的对象都保留在该池中直到应用程序终止?

2) 如果 1 为真,是否在没有本地自动释放池的情况下创建自动释放对象(因此将该对象放置在 main.m 池中)将该对象保留在内存中直到应用程序终止或收到内存警告?

3) main.m 自动释放池什么时候被清空,除了应用程序收到内存警告或应用程序终止时?

例如,在这样的 cellForRowAtIndexPath 委托(delegate)方法中:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Foobar"];
if (cell == nil) {
    // No cell to reuse => create a new one
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Foobar"] autorelease];

    // lots of custom stuff
}

return cell;

细胞何时真正释放?它们必须是自动释放的,因为你不能在返回它们之前释放它们,你也不能在返回它们之后释放它们,因为它们超出了范围。根据我目前的理解,细胞被放置在最顶层的自动释放池中,并在该池被排空/释放时释放。在这种情况下,那将是应用程序中唯一的自动释放池; main 中的那个。

4) 问题在于,即使我处理完这些单元格并且 View Controller 已被释放,单元格仍保留在内存中,是吗?如果不是这种情况,有人可以解释这种情况下的内存管理是如何工作的吗?谢谢!

注意:我看过 Apple 的文档,但它主要讨论何时使用您自己的本地自动释放池,但很少讨论它们的实际功能。

最佳答案

来自documentation :

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

因此,默认池中的自动释放对象只会在当前事件的持续时间内存活。

关于objective-c - Objective-C 中的自动释放池 - 释放主自动释放池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549711/

相关文章:

ios - 作为 Y 的子类的类型 X 的向下转换集

c - 确定通过 HeapAlloc() 分配的数组的大小

c++ - 使用(连同)realloc 调用构造函数

objective-c - 希望编写一个 4 路温度转换器 Objective-C 控制台程序

objective-c - 停止自动调用 ios5 生命周期事件

ios - React Native 和字体变体

iphone - 如何在后台线程上定期从服务器轮询数据?

c++ - 如何使用 C/C++ 系统调用获取 Linux 中进程的当前堆内存大小?

ios - 来自 iOS 应用程序/Objective-C 的 Google Fusion Tables?

objective-c - Objective-C/中 drain、release、dealloc 和 retain 之间的区别