随着ARC技术的使用,iOS的开发者在内存管理方面越来越方便,很多的事情已经不需要我们来操作,编译器已经帮我们做好了。即使是这样有些还是要了解的,以便我们犯一些低级的错误,造成内存泄露甚至崩溃,今天来说说autoreleasepool的那些事。
来看个常见的面试题:常常会问下面的代码有什么问题,怎么解决?如果你对autoreleasepool不了解的话就很难发现问题。
for (int i = 0; i < 1000000; i++) {
NSNumber *num = [NSNumber numberWithInt:i];
}
main函数中的@autoreleasepool{}
看下我们最常见的main函数中的代码,用clang编译之后:@autoreleasepool{...}
被编译成了{__AtAutoreleasePool __autoreleasepool; ... }
当进入main函数之后,由于主线程的runloop是开启的,就会一直处于主线程的runloop内,直到runloop结束也就是程序退出了。
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
...
}
return 0;
}
下面来看下__AtAutoreleasePoo
l是什么?一个结构体。 在创建__AtAutoreleasePool
结构体变量的时候调用了objc_autoreleasePoolPush(void)
,销毁的时候会调动objc_autoreleasePoolPop(void *)
;在上面的main函数中__autoreleasepool结构变量超出右}的作用域就会释放,但是同时程序也退出了,操作系统同时也会把程序所占用的内存都释放掉,所以从技术角度来看并不是非要有个@autoreleasepool{}
。那么问题来了:这里为什么要加@autoreleasepool{}
,感觉没必要?技术上是可行的,去掉main函数中的@autoreleasepool{}
并没有什么关系,但是为了严谨,为了使UIApplicationMin创建出来的自动释放对象有自动释放池可添加,并能在自动释放池结束的时候释放对象而不是依赖操作系统的回收,所以加上@autoreleasepool{}
,可以把它理解为最外层才自动释放池。
extern "C" __declspec(dllimport) void * objc_autoreleasePoolPush(void);
extern "C" __declspec(dllimport) void objc_autoreleasePoolPop(void *);
struct __AtAutoreleasePool {
__AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
void * atautoreleasepoolobj;
};
由下面的AutoreleasePoolPage
类,可以看出AutoreleasePoolPage
是一个C++类,且AutoreleasePoolPage
是一个双向链表,存在child和parent两个链接。
另外苹果开源的相关代码中也能查到响应的资料:API地址
MRC和ARC下的自动释放池
再来看下MRC下常写的一些代码:obj随着pool的drain也会释放掉,那么NSAutoreleasePool到底做了什么呢?
//相当于调用objc_autoreleasePoolPush()即 class AutoreleasePoolPage的push()
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id obj = [[NSObject alloc] init];
//相当于调用rootAutorelease2(obj)即 class AutoreleasePoolPage的autorelease(obj)
[obj autorelease];
//相当于调用objc_autoreleasePoolPop(pool)即 class AutoreleasePoolPage的pop()
[pool drain];
class AutoreleasePoolPage
{
...
static size_t const COUNT = SIZE / sizeof(id);
magic_t const magic;
id *next;
pthread_t const thread;
AutoreleasePoolPage * const parent;
AutoreleasePoolPage *child;
uint32_t const depth;
uint32_t hiwat;
static inline void *push()
{
//生成并持有NSAutoreleasepool对象
}
static inline void pop(void *token)
{
//释放NSAutoreleasepool对象
}
static inline id autorelease(id obj)
{
//加入到内部数组中,并在pool销毁的时候接受release消息
}
...
}
void *objc_autoreleasePoolPush(void)
{
return AutoreleasePoolPage::push();
}
void objc_autoreleasePoolPop(void *ctxt)
{
AutoreleasePoolPage::pop(ctxt);
}
objc_object::rootAutorelease2()
{
assert(!isTaggedPointer());
return AutoreleasePoolPage::autorelease((id)this);
}
在ARC中用@autoreleasepool{...}
替换了MRC下的NSAutoreleasePool,如:
MRC:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id obj = [[NSObject alloc] init];
[obj autorelease];
[pool drain];
ARC:
@autoreleasepool{
id __autoreleasing obj = [[NSObject alloc] init];
}
上面代码是等价的。加上__autoreleasing是为了标识obj是autoreleasing的,编译器会把它加到自动释放池中。在ARC下用alloc、new、copy、mutableCopy之外的方法获取对象,编译器才会默认帮我们加入到自动释放池中,所以上面的obj要加__autoreleasing,但是一般不这样写,这里只是为了展示对等的代码。
线程和@autoreleasepool{}
上面的AutoreleasePoolPage
类,可以看出pthread_t const thread
变量,也就是说@autoreleasepool{}
离不开线程而存在。我们也都知道主线程的runloop默认是开启的,其他子线程的runloop默认不开启。
APP启动的时候会在主线程注册两个observer,一个监听即将进入runloop事件,一个监听runloop即将休眠和即将退出两个事件,runloop的相关知识推荐这个文章runloop链接,当即将创建runloop的时候会创建@autoreleasepool{}
,在runloop即将休眠和即将退出的时候会销毁@autoreleasepool{}
释放自动释放池,并释放autorelease对象。所以可以看到@autoreleasepool{}
不仅仅和线程有关系而且和runloop有着直接的关系。更具体的如何释放以及autoreleasePage结构问题推荐这篇文章autoreleasepool链接
或许你会问那么子线程呢?默认不开启runloop,若用到了autorelease对象会造成内存泄露吗?作者也有如此疑问,这篇文章Autorelease 对象的内存管理,作者给出了明确的答案: OS X 10.9+和 iOS 7+不会造成内存泄露,当子线程未开启runloop的时候而你用到了autorelease对象会调用 autoreleaseNoPage 方法,这个方法会为你创建一个hotpage(可以理解为当前正在使用的autoreleasePoolPage),并调用page->add(obj)
将autorelease对象加入到自动释放池中,这样就不会造成内存泄露了!
这个是autoreleaseNoPage
的源码:
static __attribute__((noinline))
id *autoreleaseNoPage(id obj)
{
// "No page" could mean no pool has been pushed
// or an empty placeholder pool has been pushed and has no contents yet
assert(!hotPage());
bool pushExtraBoundary = false;
if (haveEmptyPoolPlaceholder()) {
// We are pushing a second pool over the empty placeholder pool
// or pushing the first object into the empty placeholder pool.
// Before doing that, push a pool boundary on behalf of the pool
// that is currently represented by the empty placeholder.
pushExtraBoundary = true;
}
else if (obj != POOL_BOUNDARY && DebugMissingPools) {
// We are pushing an object with no pool in place,
// and no-pool debugging was requested by environment.
_objc_inform("MISSING POOLS: (%p) Object %p of class %s "
"autoreleased with no pool in place - "
"just leaking - break on "
"objc_autoreleaseNoPool() to debug",
pthread_self(), (void*)obj, object_getClassName(obj));
objc_autoreleaseNoPool(obj);
return nil;
}
else if (obj == POOL_BOUNDARY && !DebugPoolAllocation) {
// We are pushing a pool with no pool in place,
// and alloc-per-pool debugging was not requested.
// Install and return the empty pool placeholder.
return setEmptyPoolPlaceholder();
}
// We are pushing an object or a non-placeholder'd pool.
// Install the first page.
AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
setHotPage(page);
// Push a boundary on behalf of the previously-placeholder'd pool.
if (pushExtraBoundary) {
page->add(POOL_BOUNDARY);
}
// Push the requested object or pool.
return page->add(obj);
}
开头问题的解答。
看到这里你是否明白了开篇所说的问题所在?当一次运行循环结束之前,也就是autoreleasepool释放autorelease对象之前,autoreleasepool的内存一直在增加,APP会出现内存峰值,卡顿,甚至会被系统强制关闭造成crash。来验证一下:
不加@autoreleasepool的情况
加上@autoreleasepool的情况
所以加上@autoreleasepool
保证每次循环生成的autorelease对象及时的释放才能避免上述问题:
for (int i = 0; i < 1000000; i++) {
@autoreleasepool {
NSNumber *num = [NSNumber numberWithInt:i];
NSLog(@"%@", num);
}
}
另外@autoreleasepool
还有延迟释放,使对象超出函数作用域存在等用处。
以上是作者精心准备的关于自动释放池的知识点,笔记与学习并用,有不足之处还望指正!
参考:
《Objective-C高级编程》
Autorelease 对象的内存管理,