weak指针
我们通常会使用__weak
来对变量进行弱引用,被__weak
修饰的变量一旦被释放,会自动置为nil
__unsafe_unretained
的作用也是将变量变成弱指针,但是不同于__weak
的原因是修饰的变量释放后并不会置为nil
weak的实现原理
我们可以在dealloc析构函数
的实现中找到关于弱引用的处理
根据调用轨迹dealloc -> _objc_rootDealloc -> rootDealloc -> object_dispose -> objc_destructInstance -> clearDeallocating -> clearDeallocating_slow
找到clearDeallocating_slow
来分析
NEVER_INLINE void
objc_object::clearDeallocating_slow()
{
ASSERT(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
SideTable& table = SideTables()[this];
table.lock();
if (isa.weakly_referenced) {
// 清空弱引用表
weak_clear_no_lock(&table.weak_table, (id)this);
}
if (isa.has_sidetable_rc) {
// 清空引用计数
table.refcnts.erase(this);
}
table.unlock();
}
如果有弱引用表,则进一步调用weak_clear_no_lock
去清空弱引用表
void
weak_clear_no_lock(weak_table_t *weak_table, id referent_id)
{
// 当前对象的地址值
objc_object *referent = (objc_object *)referent_id;
// 通过地址值找到弱引用表
weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);
if (entry == nil) {
/// XXX shouldn't happen, but does with mismatched CF/objc
//printf("XXX no entry for clear deallocating %p\n", referent);
return;
}
// zero out references
weak_referrer_t *referrers;
size_t count;
if (entry->out_of_line()) {
referrers = entry->referrers;
count = TABLE_SIZE(entry);
}
else {
referrers = entry->inline_referrers;
count = WEAK_INLINE_COUNT;
}
for (size_t i = 0; i < count; ++i) {
objc_object **referrer = referrers[i];
if (referrer) {
if (*referrer == referent) {
*referrer = nil;
}
else if (*referrer) {
_objc_inform("__weak variable at %p holds %p instead of %p. "
"This is probably incorrect use of "
"objc_storeWeak() and objc_loadWeak(). "
"Break on objc_weak_error to debug.\n",
referrer, (void*)*referrer, (void*)referent);
objc_weak_error();
}
}
}
// 移除弱引用表
weak_entry_remove(weak_table, entry);
}
其内部会调用weak_entry_for_referent
根据对象的地址值作为key
,和mask进行按位与运算
在散列表中找到对应的弱引用表
static weak_entry_t *
weak_entry_for_referent(weak_table_t *weak_table, objc_object *referent)
{
ASSERT(referent);
weak_entry_t *weak_entries = weak_table->weak_entries;
if (!weak_entries) return nil;
// 利用地址值(作为key) & mask = 索引
size_t begin = hash_pointer(referent) & weak_table->mask;
size_t index = begin;
size_t hash_displacement = 0;
while (weak_table->weak_entries[index].referent != referent) {
index = (index+1) & weak_table->mask;
if (index == begin) bad_weak_table(weak_table->weak_entries);
hash_displacement++;
if (hash_displacement > weak_table->max_hash_displacement) {
return nil;
}
}
return &weak_table->weak_entries[index];
}
通过源码分析,我们可以得知weak修饰
的属性都会存在一个weak_table
类型的散列表中,然后以当前对象的地址值为key
将所有的弱引用表进行存储;当该对象被释放时,也是同样的步骤从散列表weak_table
中查找到弱引用表并移除
总结:
- 全局共维护一张
SideTables表
SideTables
中包含多个SideTable
,可以通过对象地址的哈希算法找到对应的SideTable
SideTable
对应着多个对象,里面存储着引用计数表
和弱引用表
,需要再对该对象进行一次哈希才能找到其引用计数表
和弱引用表
SideTable
的关系如下图所示

autorelease
我们在MRC环境
下给一个对象加上autorelease
,该对象会在被放到自动释放池中自动进行引用计数管理
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p1 = [[[Person alloc] init] autorelease];
}
return 0;
}
autorelease
到底做了什么呢?
@autoreleasepool的实现原理
下面我们就来分析@autoreleasepool
的实现原理
我们先将这段代码转为C++
代码来查看
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
MJPerson *person = ((MJPerson *(*)(id, SEL))(void *)objc_msgSend)((id)((MJPerson *(*)(id, SEL))(void *)objc_msgSend)((id)((MJPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("MJPerson"), sel_registerName("alloc")), sel_registerName("init")), sel_registerName("autorelease"));
}
return 0;
}
发现会生成一个__AtAutoreleasePool
类型的结构体,其内部会生成构造函数和析构函数
struct __AtAutoreleasePool {
__AtAutoreleasePool() { // 构造函数,在生成结构体变量的时候调用
atautoreleasepoolobj = objc_autoreleasePoolPush();
}
~__AtAutoreleasePool() { // 析构函数,在结构体销毁的时候调用
objc_autoreleasePoolPop(atautoreleasepoolobj);
}
void * atautoreleasepoolobj;
};
@autoreleasepool
的实现过程就是在代码块的开头和结尾分别调用objc_autoreleasePoolPush
和objc_autoreleasePoolPop
然后我们在从objc4源码
中NSObject.mm
可以找到对应的实现
void *
objc_autoreleasePoolPush(void)
{
return AutoreleasePoolPage::push();
}
void
objc_autoreleasePoolPop(void *ctxt)
{
AutoreleasePoolPage::pop(ctxt);
}
我们发现两个函数都会调用到AutoreleasePoolPage类型
,我们可以看到该类型的定义如下,本质是一个AutoreleasePoolPageData
类型的结构体
class AutoreleasePoolPage : private AutoreleasePoolPageData
{
friend struct thread_data_t;
public:
// 每页的大小
static size_t const SIZE =
#if PROTECT_AUTORELEASEPOOL
PAGE_MAX_SIZE; // must be multiple of vm page size
#else
PAGE_MIN_SIZE; // size and alignment, power of 2
#endif
private:
static pthread_key_t const key = AUTORELEASE_POOL_KEY;
static uint8_t const SCRIBBLE = 0xA3; // 0xA3A3A3A3 after releasing
static size_t const COUNT = SIZE / sizeof(id);
static size_t const MAX_FAULTS = 2;
....
}
// AutoreleasePoolPageData
struct AutoreleasePoolPageData
{
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
struct AutoreleasePoolEntry {
uintptr_t ptr: 48;
uintptr_t count: 16;
static const uintptr_t maxCount = 65535; // 2^16 - 1
};
static_assert((AutoreleasePoolEntry){ .ptr = MACH_VM_MAX_ADDRESS }.ptr == MACH_VM_MAX_ADDRESS, "MACH_VM_MAX_ADDRESS doesn't fit into AutoreleasePoolEntry::ptr!");
#endif
magic_t const magic;
__unsafe_unretained id *next;
pthread_t const thread;
AutoreleasePoolPage * const parent; // 指向上一个AutoreleasePoolPage的指针(链表中的第一个为nil)
AutoreleasePoolPage *child; // 指向下一个存储AutoreleasePoolPage的指针(链表中的最后一个为nil)
uint32_t const depth;
uint32_t hiwat;
AutoreleasePoolPageData(__unsafe_unretained id* _next, pthread_t _thread, AutoreleasePoolPage* _parent, uint32_t _depth, uint32_t _hiwat)
: magic(), next(_next), thread(_thread),
parent(_parent), child(nil),
depth(_depth), hiwat(_hiwat)
{
}
};
总结
@autoreleasepool
底层会生成一个__AtAutoreleasePool的对象
__AtAutoreleasePool
内部又会分别生成两个函数objc_autoreleasePoolPush
和objc_autoreleasePoolPop
,分别在大括号作用域的开始和结尾进行push(入栈)
和pop(出栈)
操作
__AtAutoreleasePool
的底层都是依靠AutoreleasePoolPage对象
来进行操作的
AutoreleasePoolPage
是一个双向链表的结构,其内部的child
会指向下一个AutoreleasePoolPage对象
;parent
会指向上一个AutoreleasePoolPage对象
objc_autoreleasePoolPush的源码分析
我们通过调用轨迹objc_autoreleasePoolPush -> AutoreleasePoolPage::push
来分析内部具体做了什么
// 入栈
static inline void *push()
{
id *dest;
if (slowpath(DebugPoolAllocation)) {
// Each autorelease pool starts on a new pool page.
// 创建一个新的page对象,将POOL_BOUNDARY加进去
dest = autoreleaseNewPage(POOL_BOUNDARY);
} else {
// 已有page对象,快速加入POOL_BOUNDARY
dest = autoreleaseFast(POOL_BOUNDARY);
}
ASSERT(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
return dest;
}
【第一步】如果没有新的page对象,那么会调用autoreleaseNewPage
static __attribute__((noinline))
id *autoreleaseNewPage(id obj)
{
// 获取当前操作页
AutoreleasePoolPage *page = hotPage();
// 将POOL_BOUNDARY加到page中(入栈)
if (page) return autoreleaseFullPage(obj, page);
else return autoreleaseNoPage(obj);
}
// 获取当前操作页
static inline AutoreleasePoolPage *hotPage()
{
// 获取当前页
AutoreleasePoolPage *result = (AutoreleasePoolPage *)
tls_get_direct(key);
// 如果是一个空池,则返回nil,否则,返回当前线程的自动释放池
if ((id *)result == EMPTY_POOL_PLACEHOLDER) return nil;
if (result) result->fastcheck();
return result;
}
autoreleaseNewPage
内部又会分别判断有page和没有page的操作
1.有page就调用autoreleaseFullPage
将对象压入栈
static __attribute__((noinline))
id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
{
// The hot page is full.
// Step to the next non-full page, adding a new page if necessary.
// Then add the object to that page.
ASSERT(page == hotPage());
ASSERT(page->full() || DebugPoolAllocation);
// 循环遍历当前page是否满了
do {
// 如果子页面存在,则将页面替换为子页面
if (page->child) page = page->child;
// 如果子页面不存在,则新建页面
else page = new AutoreleasePoolPage(page);
} while (page->full());
// 设置为当前操作page
setHotPage(page);
// 压入栈
return page->add(obj);
}
// 设置当前操作页
static inline void setHotPage(AutoreleasePoolPage *page)
{
if (page) page->fastcheck();
tls_set_direct(key, (void *)page);
}
static inline AutoreleasePoolPage *coldPage()
{
AutoreleasePoolPage *result = hotPage();
if (result) {
while (result->parent) {
result = result->parent;
result->fastcheck();
}
}
return result;
}
在add
里进行真正的压栈操作
id *add(id obj)
{
ASSERT(!full());
unprotect();
id *ret; // 对象存储的位置
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
if (!DisableAutoreleaseCoalescing || !DisableAutoreleaseCoalescingLRU) {
if (!DisableAutoreleaseCoalescingLRU) {
if (!empty() && (obj != POOL_BOUNDARY)) {
AutoreleasePoolEntry *topEntry = (AutoreleasePoolEntry *)next - 1;
for (uintptr_t offset = 0; offset < 4; offset++) {
AutoreleasePoolEntry *offsetEntry = topEntry - offset;
if (offsetEntry <= (AutoreleasePoolEntry*)begin() || *(id *)offsetEntry == POOL_BOUNDARY) {
break;
}
if (offsetEntry->ptr == (uintptr_t)obj && offsetEntry->count < AutoreleasePoolEntry::maxCount) {
if (offset > 0) {
AutoreleasePoolEntry found = *offsetEntry;
memmove(offsetEntry, offsetEntry + 1, offset * sizeof(*offsetEntry));
*topEntry = found;
}
topEntry->count++;
ret = (id *)topEntry; // need to reset ret
goto done;
}
}
}
} else {
if (!empty() && (obj != POOL_BOUNDARY)) {
AutoreleasePoolEntry *prevEntry = (AutoreleasePoolEntry *)next - 1;
if (prevEntry->ptr == (uintptr_t)obj && prevEntry->count < AutoreleasePoolEntry::maxCount) {
prevEntry->count++;
ret = (id *)prevEntry; // need to reset ret
goto done;
}
}
}
}
#endif
// 传入对象存储的位置
ret = next; // faster than `return next-1` because of aliasing
// 将obj压栈到next指针位置,然后next进行++,即下一个对象存储的位置
*next++ = obj;
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
// Make sure obj fits in the bits available for it
ASSERT(((AutoreleasePoolEntry *)ret)->ptr == (uintptr_t)obj);
#endif
done:
protect();
return ret;
}
2.在autoreleaseNewPage
内部判断没有page就会去调用autoreleaseNoPage
创建新的page,然后在进行压栈操作
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;
// 判断是否为空占位符,如果是,则将入栈标识为true
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;
}
// 如果不是POOL_BOUNDARY,并且没有pool,则报错
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",
objc_thread_self(), (void*)obj, object_getClassName(obj));
objc_autoreleaseNoPool(obj);
return nil;
}
// 如果对象是POOL_BOUNDARY,且没有申请自动释放池内存,则设置一个空占位符存储在tls中,其目的是为了节省内存
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.
// 如果标识为true,则压入栈
if (pushExtraBoundary) {
page->add(POOL_BOUNDARY);
}
// Push the requested object or pool.
return page->add(obj);
}
【第二步】 如果一开始就有page页面,那么直接进入到autoreleaseFast
,再分别进行判断
static inline id *autoreleaseFast(id obj)
{
AutoreleasePoolPage *page = hotPage();
if (page && !page->full()) { // 已有page,并且没满
return page->add(obj);
} else if (page) {
// 如果满了,则安排新的page
return autoreleaseFullPage(obj, page);
} else {
// page不存在,新建
return autoreleaseNoPage(obj);
}
}
总结
- 每一个
AutoreleasePoolPage对象
都会有一定的存储空间,大概占用4096个字节
- 每一个
AutoreleasePoolPage对象
内部的成员变量会占56个字节
,然后剩余的空间才用来存储autorelease对象
- 每一个
@autoreleasePool
的开始都会先将POOL_BOUNDARY对象
压入栈,然后才开始存储autorelease对象
,并且push方法
会返回POOL_BOUNDARY对象
的内存地址
- 当一个
AutoreleasePoolPage对象
存满后才会往下一个AutoreleasePoolPage对象
里开始存储
AutoreleasePoolPage对象
里面的begin
和end
分别对应着autorelease对象
开始入栈的起始地址和结束地址
AutoreleasePoolPage对象
里面的next
指向下一个能存放autorelease
对象地址的区域
上面整个push入栈
的过程分析可以用下图来概述

autorelease的源码分析
下面我们来看一下autorelease
底层做了什么
// objc_object::autorelease
inline id
objc_object::autorelease()
{
ASSERT(!isTaggedPointer());
if (fastpath(!ISA()->hasCustomRR())) {
return rootAutorelease();
}
return ((id(*)(objc_object *, SEL))objc_msgSend)(this, @selector(autorelease));
}
// objc_object::rootAutorelease
inline id
objc_object::rootAutorelease()
{
// 如果是TaggedPointer就返回
if (isTaggedPointer()) return (id)this;
if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this;
return rootAutorelease2();
}
// objc_object::rootAutorelease2
__attribute__((noinline,used))
id
objc_object::rootAutorelease2()
{
ASSERT(!isTaggedPointer());
return AutoreleasePoolPage::autorelease((id)this);
}
发现最后还是会调用到AutoreleasePoolPage
的autorelease
static inline id autorelease(id obj)
{
ASSERT(!obj->isTaggedPointerOrNil());
id *dest __unused = autoreleaseFast(obj);
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
ASSERT(!dest || dest == EMPTY_POOL_PLACEHOLDER || (id)((AutoreleasePoolEntry *)dest)->ptr == obj);
#else
ASSERT(!dest || dest == EMPTY_POOL_PLACEHOLDER || *dest == obj);
#endif
return obj;
}
然后进入到快速压栈autoreleaseFast
进行压栈操作,autoreleasepool
只会将调用了autorelease
的对象压入栈
autorelease
和objc_autoreleasePush
的整体分析如下图所示

objc_autoreleasePoolPop的源码分析
【第一步】我们通过调用轨迹objc_autoreleasePoolPop -> AutoreleasePoolPage::pop
来分析内部具体做了什么
static inline void
pop(void *token)
{
AutoreleasePoolPage *page;
id *stop;
// 判断是否为空占位符
if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
// Popping the top-level placeholder pool.
// 获取当前页
page = hotPage();
if (!page) {
// Pool was never used. Clear the placeholder.
// 如果当前页不存在,则清除空占位符
return setHotPage(nil);
}
// Pool was used. Pop its contents normally.
// Pool pages remain allocated for re-use as usual.
// 如果当前页存在,则将当前页设置为coldPage,token设置为coldPage的开始位置
page = coldPage();
token = page->begin();
} else {
// 获取token所在的page
page = pageForPointer(token);
}
stop = (id *)token;
// 判断最后一个位置,是否是POOL_BOUNDARY
if (*stop != POOL_BOUNDARY) {
// 如果不是,即最后一个位置是一个对象
if (stop == page->begin() && !page->parent) {
// Start of coldest page may correctly not be POOL_BOUNDARY:
// 1. top-level pool is popped, leaving the cold page in place
// 2. an object is autoreleased with no pool
// 如果是第一个位置,且没有父节点,什么也不做
} else {
// Error. For bincompat purposes this is not
// fatal in executables built with old SDKs.
// 如果是第一个位置,且有父节点,则出现了混乱
return badPop(token);
}
}
if (slowpath(PrintPoolHiwat || DebugPoolAllocation || DebugMissingPools)) {
return popPageDebug(token, page, stop);
}
// 出栈
return popPage<false>(token, page, stop);
}
begin
和end
分别对应着autorelease对象
的起始地址和结束地址
// 开始存放autorelease对象的地址:开始地址 + 他本身占用的大小
id * begin() {
return (id *) ((uint8_t *)this+sizeof(*this));
}
// 结束地址:开始地址 + PAGE_MAX_SIZE
id * end() {
return (id *) ((uint8_t *)this+SIZE);
}
// coldPage
static inline AutoreleasePoolPage *coldPage()
{
AutoreleasePoolPage *result = hotPage();
if (result) {
while (result->parent) {
result = result->parent;
result->fastcheck();
}
}
return result;
}
【第二步】然后进入popPage
进行出栈操作
template<bool allowDebug>
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();
}
}
}
// kill
void kill()
{
// Not recursive: we don't want to blow out the stack
// if a thread accumulates a stupendous amount of garbage
AutoreleasePoolPage *page = this;
while (page->child) page = page->child;
AutoreleasePoolPage *deathptr;
do {
deathptr = page;
// 子节点 变成 父节点
page = page->parent;
if (page) {
page->unprotect();
//子节点置空
page->child = nil;
page->protect();
}
delete deathptr;
} while (deathptr != this);
}
内部会调用releaseUntil
循环遍历进行pop操作
void releaseUntil(id *stop)
{
// Not recursive: we don't want to blow out the stack
// if a thread accumulates a stupendous amount of garbage
// 循环遍历
// 判断下一个对象是否等于stop,如果不等于,则进入while循环
while (this->next != stop) {
// Restart from hotPage() every time, in case -release
// autoreleased more objects
AutoreleasePoolPage *page = hotPage();
// fixme I think this `while` can be `if`, but I can't prove it
// 如果当前页是空的
while (page->empty()) {
// 将page赋值为父节点页
page = page->parent;
// 并设置当前页为父节点页
setHotPage(page);
}
page->unprotect();
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
AutoreleasePoolEntry* entry = (AutoreleasePoolEntry*) --page->next;
// create an obj with the zeroed out top byte and release that
id obj = (id)entry->ptr;
int count = (int)entry->count; // grab these before memset
#else
id obj = *--page->next;
#endif
memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
page->protect();
if (obj != POOL_BOUNDARY) { // 只要不是POOL_BOUNDARY,就进行release
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
// release count+1 times since it is count of the additional
// autoreleases beyond the first one
for (int i = 0; i < count + 1; i++) {
objc_release(obj);
}
#else
objc_release(obj);
#endif
}
}
// 设置当前页
setHotPage(this);
#if DEBUG
// we expect any children to be completely empty
for (AutoreleasePoolPage *page = child; page; page = page->child) {
ASSERT(page->empty());
}
#endif
}
总结
pop
函数会将POOL_BOUNDARY
的内存地址传进去
autorelease对象
从end的结束地址
开始进行发送release消息
,一直找到POOL_BOUNDARY
为止
- 一旦发现当前页已经空了,就会去上一个页面进行
pop
,并释放当前页面
- 整个入栈出栈的顺序是采用先进后出,和栈中顺序一样,但不代表着这里说的是真正的栈
上面整个pop
出栈的过程分析可以用下图来概述

通过打印分析执行过程
我们可以通过一个私有函数_objc_autoreleasePoolPrint
来打印分析整个autorelease
的过程
// 声明内部私有函数,可以调用执行
extern void _objc_autoreleasePoolPrint(void);
int main(int argc, const char * argv[]) {
@autoreleasepool { // r1 = push()
Person *p1 = [[[Person alloc] init] autorelease];
Person *p2 = [[[Person alloc] init] autorelease];
@autoreleasepool { // r2 = push()
MJPerson *p3 = [[[Person alloc] init] autorelease];
_objc_autoreleasePoolPrint();
} // pop(r2)
} // pop(r1)
return 0;
}
可以看到打印结果如下
objc[25057]: ##############
objc[25057]: AUTORELEASE POOLS for thread 0x1000e7e00
objc[25057]: 5 releases pending.
objc[25057]: [0x107009000] ................ PAGE (hot) (cold)
objc[25057]: [0x107009038] ################ POOL 0x107009038
objc[25057]: [0x107009040] 0x10060f120 Person
objc[25057]: [0x107009048] 0x100606800 Person
objc[25057]: [0x107009050] ################ POOL 0x107009050
objc[25057]: [0x107009058] 0x100607de0 Person
objc[25057]: ##############
面试题
1.@dynamic和@synthesize两个关键字的含义
在旧版的编译器,加上@synthesize
会生成带下划线的成员变量和setter、getter的实现
,现在的编译器已经不用加上这个关键字也可以自动实现了
// 成员变量为_age
@synthesize age = _age;
// 不赋值的话,成员变量就是age
@synthesize age
加上@dynamic
不会自动生成setter和getter的实现和成员变量
@dynamic age;
所有的声明都是由@property
来决定的
2.分别运行下面两段代码,思考能发生什么事,有什么区别
@interface ViewController ()
@property (strong, nonatomic) NSString *name;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// 第一段
for (int i = 0; i < 1000; i++) {
dispatch_async(queue, ^{
self.name = [NSString stringWithFormat:@"abcdefghijk"];
});
}
// 第二段
for (int i = 0; i < 1000; i++) {
dispatch_async(queue, ^{
self.name = [NSString stringWithFormat:@"abc"];
});
}
}
@end
【第一段代码】
由于给self.name
赋值会调用name的setter
,setter
的实现是先释放掉旧的成员变量,然后赋值新的成员变量;又因为是多线程并发调用,所以name
被多次释放造成坏内存访问
解决办法:在dispatch_async
的回调中给self.name
赋值加锁
【第二段代码】
程序不会崩溃。
我们先分别打印两个字符串,从打印类型和内存地址都可以发现第二个字符串是经过了TaggedPointer
优化过的,所以不会调用setter
,也就不会被多次释放造成崩溃了
NSString *str1 = [NSString stringWithFormat:@"abcdefghijk"];
NSString *str2 = [NSString stringWithFormat:@"abc"];
NSLog(@"%@ %@", [str1 class], [str2 class]);
NSLog(@"%p %p", str1, str2);
// 输出:__NSCFString NSTaggedPointerString
// 0x600000a8d6c0 0x818ff819168b363d
3.ARC都帮我们做了什么
ARC
是LLVM
和Runtime
相互协作的产物;LLVM
会在编译阶段帮我们生成内存管理相关的代码,Runtime
又会在运行时进行内存管理的操作
4.局部变量具体是在什么时候进行释放的
- 如果是不被修饰的局部变量,会在函数内作用域结束进行释放
- 如果是被
@autoreleasePool
修饰的,那么会交由自动释放池管理
- 如果是调用了
autorelease
,那么会被加到RunLoop
中进行管理
看下面这段代码,对象在执行完viewWillAppear
后才被释放
- (void)viewDidLoad {
[super viewDidLoad];
Person *person = [[[Person alloc] init] autorelease];
NSLog(@"%s", __func__);
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"%s", __func__);
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"%s", __func__);
}
Runloop
在进入循环时会先执行一次objc_autoreleasePoolPush
,然后再进入睡眠之前会执行一次objc_autoreleasePoolPop
和objc_autoreleasePoolPush
,就这样一直循环;等到程序真正退出时再回执行一次objc_autoreleasePoolPop
由此也可以发现viewDidLoad
和viewWillAppear
是在同一次运行循环中
原文链接:http://www.cnblogs.com/funkyRay/p/ios-di-ceng-yuan-li-ba-nei-cun-guan-li-xia.html