十三、AutoreleasePool是被嵌套的!
池是被嵌套的,嵌套的结果是个栈,同一线程只有当前栈顶pool实例是可用的:
| pool_3 |
| --------- |
| pool_2 |
| --------- |
| pool_1 |
|_______|
其代码如下:
代码:
NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool *pool3 = [[NSAutoreleasePool alloc] init];
NSObject *o = [[NSObject alloc] init] autorelease];
[pool3 release];
[pool2 release];
[pool1 release];
NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool *pool3 = [[NSAutoreleasePool alloc] init];
NSObject *o = [[NSObject alloc] init] autorelease];
[pool3 release];
[pool2 release];
[pool1 release];
我们可以看到其栈顶是pool3,o的autorelease是把当前的release放在栈顶的pool实例管理。。。也就是pool3。
在生命周期短,产生大量放在autoreleasePool中管理实例的情况下经常用此方法减少内存使用,达到内存及时回收的目的。