iOS 中AutoreleasePool实现原理上

我们都知道iOS的内存管理分为手动内存管理(MRC)和自动内存管理(ARC),但是不管是手动内存管理还是自动内存管理,自动释放池在其中都起到至关重要的作用

我们首先看下官方文档对自动释放池的定义:

An object that supports Cocoa’s reference-counted memory management system.

从官方的定义中我们可以知道,自动释放池就是一个系统OC对象,它是作用于内存管理中

下面我们先来分析官方文档中对自动释放池的一些解释说明,这样对我们深刻理解自动释放池的工作原理非常有帮助

官方文档地址:

我们先来看下官方对自动释放池的声明:

@interface NSAutoreleasePool : NSObject

在手动内存管理和自动内存管理模式下,创建自动释放池的写法也有所不同,

MRC模式下

    // 创建一个自动释放池
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSObject *obj = [[NSObject alloc] init];
    
    // 将对象添加到自动释放池
    [obj autorelease];
    
    // 销毁自动释放池,等同于`[pool release];`写法,但是`[pool release]`和`[pool drain]`又有一些不同,后面会讲到不同点
    [pool drain];

或者

@autoreleasepool {
    NSObject *obj = [[NSObject alloc] init];
    
    // 将对象添加到自动释放池
    [obj autorelease];
}

ARC模式下

@autoreleasepool {
    NSObject *obj = [[NSObject alloc] init];
    
    // 将对象添加到自动释放池
    [obj autorelease];
}

从上面的创建方式我们可以看到,在ARC模式下,只能使用@autoreleasepool{}这种方式创建自动释放池,而不能使用NSAutoreleasePool这种创建OC对象的方式来创建

关于自动释放池的创建方式,官方文档也有详细的介绍说明:

Important

If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Code benefitting from a local autorelease pool.
[pool release];

you would write:

@autoreleasepool {
    // Code benefitting from a local autorelease pool.
}

@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.

在自动释放池的工作原理中,只有对象调用了autorelease方法,那么这个对象才会被添加到自动释放池中,然后当这个自动释放池调用drain方法销毁的时候,便会向池中的每一个对象发送一条release消息来销毁池中的对象,如果一个对象调用了autorelease多次,那么在自动释放池销毁后会向这个对象发送多条release消息来销毁这个对象,也就是说对象调用多少次autorelease,对象销毁时就会调用多少次release

这里说明下一个对象调用release和调用autorelease的区别:

如果一个对象调用release则会立即释放(如果引用计数减为0),如果一个对象调用autorelease则会先将这个对象放入自动释放池,等到自动释放池销毁的时候在释放这个对象。也就是说对象调用autorelease会延迟释放

对应于官方文档的解释说明如下:

In a reference-counted environment (as opposed to one which uses garbage collection), an NSAutoreleasePool object contains objects that have received an autorelease message and when drained it sends a release message to each of those objects. Thus, sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is drained (it may be longer if the object is subsequently retained). An object can be put into the same pool several times, in which case it receives a release message for each time it was put into the pool.

在引用计数的内存管理方式下,Cocoa框架希望总是有一个自动释放池可用,如果没有可用的自动释放池,那么自动释放的的对象得不到释放就会造成内存泄漏

对应于官方文档的解释说明如下:

In a reference counted environment, Cocoa expects there to be an autorelease pool always available. If a pool is not available, autoreleased objects do not get released and you leak memory. In this situation, your program will typically log suitable warning messages.

我们都知道iOS的应用程序,在程序一启动的main函数中就创建了一个自动释放池,并且在程序的主线程中添加了runloop,并且在runloop的每一个事件循环开始之前都会去创建自动释放池,当自动释放池对象调用drains时便会销毁这个自动释放池,从而释放在runloop处理事件过程中生成的所有对象。正是因为在runloop的事件循环中会自动创建自动释放池,所以我们在平时开发过程中也不太需要开发者来手动创建自动释放池,但是如果应用在runloop事件循环中创建了大量的临时自动释放对象,那么这时我们最好手动创建自动释放池,将这大量的临时对象放到手动创建的自动释放池中

对应于官方文档的解释说明如下:

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.

这里需要注意:使用[[NSAutoreleasePool alloc] init]这种方式创建的自动释放池对象,我们不能对这个自动释放池对象调用retain进行持有,我们也不能调用autorelease来释放这个自动释放池对象,我们要想销毁这个自动释放池对象,我们只能调用drain或者release。但是对于使用@autoreleasepool {}方式创建的自动释放池,它会在出了作用域后自动销毁创建的池子,不需要开发者的去调用函数销毁

对应于官方文档的解释说明如下:

You create an NSAutoreleasePool object with the usual alloc and init messages and dispose of it with drain (or release—to understand the difference, see Garbage Collection). Since you cannot retain an autorelease pool (or autorelease it—see retain and autorelease), draining a pool ultimately has the effect of deallocating it. You should always drain an autorelease pool in the same context (invocation of a method or function, or body of a loop) that it was created. See Using Autorelease Pool Blocks for more details.

我们都知道在程序的运行过程中,可能会创建很多的自动释放池,这些自动释放池在应用程序中是以栈的方式来进行维护和管理的,新创建的自动释放池会添加到栈的顶部,当需要销毁池子时,就从栈顶移除。并且每个线程都维护自己的自动释放池栈,程序的主线程中有系统创建的自动释放池,但是新创建的子线程默认是没有自动释放池的,如果子线程中需要自动释放池,则需要在子线程中手动创建自动释放池,当子线程销毁时,也会自动销毁子线程中创建的所有自动释放池。

对应于官方文档的解释说明如下:

Each thread (including the main thread) maintains its own stack of NSAutoreleasePool objects (see Threads). As new pools are created, they get added to the top of the stack. When pools are deallocated, they are removed from the stack. Autoreleased objects are placed into the top autorelease pool for the current thread. When a thread terminates, it automatically drains all of the autorelease pools associated with itself.

自动释放池与线程之间的关系,官方文档说明如下:

Threads

If you are making Cocoa calls outside of the Application Kit’s main thread—for example if you create a Foundation-only application or if you detach a thread—you need to create your own autorelease pool.

If your application or thread is long-lived and potentially generates a lot of autoreleased objects, you should periodically drain and create autorelease pools (like the Application Kit does on the main thread); otherwise, autoreleased objects accumulate and your memory footprint grows. If, however, your detached thread does not make Cocoa calls, you do not need to create an autorelease pool.

Note

If you are creating secondary threads using the POSIX thread APIs instead of NSThread objects, you cannot use Cocoa, including NSAutoreleasePool, unless Cocoa is in multithreading mode. Cocoa enters multithreading mode only after detaching its first NSThread object. To use Cocoa on secondary POSIX threads, your application must first detach at least one NSThread object, which can immediately exit. You can test whether Cocoa is in multithreading mode with the NSThread class method isMultiThreaded.

自动释放池对象调用drainrelease来销毁池子,它们二者的区别:

如果只是在引用计数环境下,那么调用drain和调用release功能上是一样的,但是如果在垃圾回收(GC)环境下,调用release等于是一个no-op操作,no-op操作可以理解为没有操作计算机指令,而调用drain则会发出一个objc_collect_if_needed的GC操作。

所以说当我们不清楚什么时候会有GC操作时,这时我们最好选择使用drain来销毁自动释放池是最为安全的。

对应于官方文档的解释说明如下:

Garbage Collection

In a garbage-collected environment, there is no need for autorelease pools. 
You may, however, write a framework that is designed to work in both a 
garbage-collected and reference-counted environment. In this case, you can use 
autorelease pools to hint to the collector that collection may be appropriate. 
In a garbage-collected environment, sending a drain message to a pool triggers
 garbage collection if necessary; release, however, is a no-op. In a reference-
counted environment, drain has the same effect as release. Typically, 
therefore, you should use drain instead of release.

上面我们对iOS的自动释放池NSAutoreleasePool的官方文档说明进行了理论性的分析和总结,下面我们就从底层源码来分析自动释放池的底层结构和实现原理

讲解示例Demo地址:

https://github.com/guangqiang-liu/11-AutoreleasePool

https://github.com/guangqiang-liu/11.1-AutoreleasePool

https://github.com/guangqiang-liu/11.2-AutoreleasePool

https://github.com/guangqiang-liu/11.3-AutoreleasePool

更多文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266