底层结构
int main(int argc, const char * argv[]) {
@autoreleasepool {
}
return 0;
}
我们通过执行xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc -fno-objc-arc main.m
,将上述代码转换成C++
struct __AtAutoreleasePool {
__AtAutoreleasePool() {
atautoreleasepoolobj = objc_autoreleasePoolPush();
}
~__AtAutoreleasePool() {
objc_autoreleasePoolPop(atautoreleasepoolobj);
}
void * atautoreleasepoolobj;
};
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
}
return 0;
}
通过C++代码我们发现,autoreleasepool是由objc_autoreleasePoolPush 和 objc_autoreleasePoolPop方法构成的一个结构体。
接下来我们来研究一下objc_autoreleasePoolPush
和objc_autoreleasePoolPop
方法的具体实现。
参照苹果开源代码,我们找到了objc_autoreleasePoolPush和objc_autoreleasePoolPop的具体实现。(https://opensource.apple.com/tarballs/objc4/)
void *
objc_autoreleasePoolPush(void)
{
return AutoreleasePoolPage::push();
}
void
objc_autoreleasePoolPop(void *ctxt)
{
AutoreleasePoolPage::pop(ctxt);
}
static inline id autorelease(id obj)
{
ASSERT(obj);
ASSERT(!obj->isTaggedPointer());
id *dest __unused = autoreleaseFast(obj);
ASSERT(!dest || dest == EMPTY_POOL_PLACEHOLDER || *dest == obj);
return obj;
}
static inline id *autoreleaseFast(id obj)
{
AutoreleasePoolPage *page = hotPage();
if (page && !page->full()) {
return page->add(obj);
} else if (page) {
return autoreleaseFullPage(obj, page);
} else {
return autoreleaseNoPage(obj);
}
}
static inline void *push()
{
id *dest;
if (slowpath(DebugPoolAllocation)) {
// Each autorelease pool starts on a new pool page.
dest = autoreleaseNewPage(POOL_BOUNDARY);
} else {
dest = autoreleaseFast(POOL_BOUNDARY);
}
ASSERT(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
return dest;
}
static void
popPage(void *token, AutoreleasePoolPage *page, id *stop)
{
if (allowDebug && PrintPoolHiwat) printHiwat();
page->releaseUntil(stop);
// memory: delete empty children
if (allowDebug && DebugPoolAllocation && page->empty()) {
// special case: delete everything during page-per-pool debugging
AutoreleasePoolPage *parent = page->parent;
page->kill();
setHotPage(parent);
} else if (allowDebug && DebugMissingPools && page->empty() && !page->parent) {
// special case: delete everything for pop(top)
// when debugging missing autorelease pools
page->kill();
setHotPage(nil);
} else if (page->child) {
// hysteresis: keep one empty child if page is more than half full
if (page->lessThanHalfFull()) {
page->child->kill();
}
else if (page->child->child) {
page->child->child->kill();
}
}
}
通过源码我们发现自动释放池的主要底层数据结构是:__AtAutoreleasePool
、AutoreleasePoolPage
调用了autorelease的对象最终都是通过AutoreleasePoolPage对象来管理的。
AutoreleasePoolPage的结构
struct AutoreleasePoolPageData
{
magic_t const magic;
__unsafe_unretained id *next;
pthread_t const thread;
AutoreleasePoolPage * const parent;
AutoreleasePoolPage *child;
uint32_t const depth;
uint32_t hiwat;
};
class AutoreleasePoolPage : private AutoreleasePoolPageData {}
每个AutoreleasePoolPage对象占用4096字节内存,除了用来存放它内部的成员变量,剩下的空间用来存放autorelease对象的地址。
所有的AutoreleasePoolPage对象通过双向链表的形式连接在一起。
- 调用push方法会将一个
POOL_BOUNDARY
入栈,并且返回其存放的内存地址 - 调用pop方法时传入一个
POOL_BOUNDARY
的内存地址,会从最后一个入栈的对象开始发送release消息,直到遇到这个POOL_BOUNDARY
- id *next指向了下一个能存放autorelease对象地址的区域
可以通过以下私有函数来查看自动释放池的情况
extern void _objc_autoreleasePoolPrint(void);
autoreleasepool与RunLoop的关系
(lldb) po [NSRunLoop mainRunLoop]
<CFRunLoop 0x6000008f0300 [0x7fff8062d610]>{wakeup port = 0x2207, stopped = false, ignoreWakeUps = false,
current mode = kCFRunLoopDefaultMode,
common modes = <CFBasicHash 0x600003aacf60 [0x7fff8062d610]>{type = mutable set, count = 2,
entries =>
0 : <CFString 0x7fff8692c2c0 [0x7fff8062d610]>{contents = "UITrackingRunLoopMode"}
2 : <CFString 0x7fff806408e0 [0x7fff8062d610]>{contents = "kCFRunLoopDefaultMode"}
}
,
common mode items = <CFBasicHash 0x600003aad230 [0x7fff8062d610]>{type = mutable set, count = 14,
entries =>
20 : <CFRunLoopObserver 0x6000005f83c0 [0x7fff8062d610]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600003abfd50 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (
0 : <0x7f9ec100f038>
)}}
22 : <CFRunLoopObserver 0x6000005f8460 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600003abfd50 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (
0 : <0x7f9ec100f038>
)}}
}
通过mainRunLoop
的打印信息,我们发现在主线程 RunLoop 里注册了两个 Observer,其回调都是 _wrapRunLoopWithAutoreleasePoolHandler()。
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
kCFRunLoopEntry = (1UL << 0),
kCFRunLoopBeforeTimers = (1UL << 1),
kCFRunLoopBeforeSources = (1UL << 2),
kCFRunLoopBeforeWaiting = (1UL << 5),
kCFRunLoopAfterWaiting = (1UL << 6),
kCFRunLoopExit = (1UL << 7),
kCFRunLoopAllActivities = 0x0FFFFFFFU
};
第一个 Observer 的activities = 0x1,即监听kCFRunLoopEntry事件,其回调内会调用 _objc_autoreleasePoolPush() 创建自动释放池。其 order 是-2147483647,优先级最高,保证创建释放池发生在其他所有回调之前。
第二个 Observer 的activities = 0xa0,即kCFRunLoopBeforeWaiting & kCFRunLoopExit两个事件
- kCFRunLoopBeforeWaiting时调用_objc_autoreleasePoolPop() 和 _objc_autoreleasePoolPush() 释放旧的自动释放池并创建新池;
- kCFRunLoopExit时调用 _objc_autoreleasePoolPop() 来释放自动释放池。其order 是 2147483647,优先级最低,保证其释放池子发生在其他所有回调之后。
总结
根据苹果官方文档中对 Using Autorelease Pool Blocks 的描述,我们知道在下面三种情况下是需要我们手动添加 autoreleasepool的:
- 如果你编写的程序不是基于 UI 框架的,比如说命令行工具;
- 如果你编写的循环中创建了大量的临时对象;
- 如果你创建了一个辅助线程。当你的线程执行时,你必须尽可能快的自己创建自动释放池;