前言
说到iOS的内存管理,大致应该分为以下几个方面:
-
NSTaggedPointer
类型 -
alloc
,retain
,release
,dealloc
,retainCount
原理 -
@autoreleasepool
原理
alloc
可以移步我的这篇文章:iOS-OC对象原理_alloc&init
@autoreleasepool
移步:iOS-OC底层-AutoReleasePool分析
TaggedPointer
TaggedPointer
一直都没找到一个比较官方的定义,俗称小对象类型。它是一种特殊的类型,特点就是它的指针是值+指针
。这是苹果做的一层优化处理,小对象类型的数据存储在常量区,所以它的释放是由系统来处理的。比如在retain
或release
中,都对这种类型做了排除处理:
if (isTaggedPointer()) return (uintptr_t)this;
在看下面的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *str0 = [NSString stringWithFormat:@"z"];
NSString *str1 = [NSString stringWithFormat:@"zezefamily.com我是zezefaily"];
}
通过LLDB
,输出一下str0
和str1
(lldb) p str0
(NSTaggedPointerString *) $2 = 0xac6d1e2074072a9f @"z"
(lldb) p str1
(__NSCFString *) $3 = 0x0000600001a24230 @"zezefamily.com我是zezefaily"
(lldb)
这里可以看到一个非常明显的不同是str0
为NSTaggedPointerString *
类型,而str1
为__NSCFString *
类型。这就是苹果的优化处理,当对象存在的内容比较小时,就被优化为一个TaggedPointer
类型,以更少的字节数来保存,同时指针也做了混淆处理,来保证值的安全。
我们可以通过源码中的混淆编解码函数,将混淆后的指针还原回来。
extern uintptr_t objc_debug_taggedpointer_obfuscator;
uintptr_t
_objc_decodeTaggedPointer_(id ptr)
{
return (uintptr_t)ptr ^ objc_debug_taggedpointer_obfuscator;
}
通过指针还原输出如下:
(lldb) p/x str0
(NSTaggedPointerString *) $4 = 0xab158b5ee1846519 @"z"
(lldb) p/x _objc_decodeTaggedPointer_(str0)
(uintptr_t) $5 = 0xa0000000000007a1
0xa0000000000007a1
指针,解析出0x7a
(ascii码:122)是这个z
,0xa
是类型信息,即1 010
->1
标识为是TaggedPointer
类型,010
->2
, 对应关系如下:
typedef uint16_t objc_tag_index_t;
enum
#endif
{
// 60-bit payloads
OBJC_TAG_NSAtom = 0,
OBJC_TAG_1 = 1,
OBJC_TAG_NSString = 2,
OBJC_TAG_NSNumber = 3,
OBJC_TAG_NSIndexPath = 4,
OBJC_TAG_NSManagedObjectID = 5,
OBJC_TAG_NSDate = 6,
// 60-bit reserved
OBJC_TAG_RESERVED_7 = 7,
// 52-bit payloads
OBJC_TAG_Photos_1 = 8,
OBJC_TAG_Photos_2 = 9,
OBJC_TAG_Photos_3 = 10,
OBJC_TAG_Photos_4 = 11,
OBJC_TAG_XPC_1 = 12,
OBJC_TAG_XPC_2 = 13,
OBJC_TAG_XPC_3 = 14,
OBJC_TAG_XPC_4 = 15,
OBJC_TAG_NSColor = 16,
OBJC_TAG_UIColor = 17,
OBJC_TAG_CGColor = 18,
OBJC_TAG_NSIndexSet = 19,
OBJC_TAG_First60BitPayload = 0,
OBJC_TAG_Last60BitPayload = 6,
OBJC_TAG_First52BitPayload = 8,
OBJC_TAG_Last52BitPayload = 263,
OBJC_TAG_RESERVED_264 = 264
};
说明:笔者对这个地址相关的东西比较懵逼,说不清楚。这里需要知道的就是有TaggedPointer
类型的存在,并且当被标记为该类型的对象会存入常量区,其内存管理是由系统决定的。
retain
在探索retain
之前我们需要先回顾下isa_t
这个联合体iOS-OC对象原理_NONPOINTER_ISA,我们知道在isa_t
中包含一个extra_rc
和has_sidetable_rc
,其中extra_rc
表示该对象的引用计数值,而has_sidetable_rc
表示是否引用了散列表,当extra_rc
空间存储的值超出范围时,会使用sidetable
(散列表进行存储),即标记为has_sidetable_rc = true
。所以这里先看下SideTable
的数据结构:
struct SideTable {
spinlock_t slock; //锁
RefcountMap refcnts; //引用计数表
weak_table_t weak_table; //弱引用表
SideTable() {
memset(&weak_table, 0, sizeof(weak_table));
}
~SideTable() {
_objc_fatal("Do not delete SideTable.");
}
void lock() { slock.lock(); }
void unlock() { slock.unlock(); }
void forceReset() { slock.forceReset(); }
// Address-ordered lock discipline for a pair of side tables.
template
static void lockTwo(SideTable *lock1, SideTable *lock2);
template
static void unlockTwo(SideTable *lock1, SideTable *lock2);
};
这里可以看到,在SideTable
散列表中包含了refcnts
引用计数表和weak_table
弱引用表。这里要注意的是:不是每个对象对应一个散列表,而是一个散列表中对应多个对象,在iOS真机下,默认创建8个SideTable。 为什么不直接全部存放在一个SideTable
里呐?这里主要是为了安全和效率,如果存在一个SideTable
,每次访问数据时,会将全部数据暴露出来,有安全隐患;同时查询的数据量庞大,导致效率变慢。
整个SideTable
数据结构图如下:
我们知道了这样一个结构之后,再开始我们的
retain
探索:
首先说
retain
,本质就是引用计数加1,即isa.extra_rc+1
,具体是怎么操作的呐,先看一下retain
的源码:
- (id)retain {
return _objc_rootRetain(self);
}
_objc_rootRetain(id obj)
{
ASSERT(obj);
return obj->rootRetain();
}
ALWAYS_INLINE id
objc_object::rootRetain()
{
return rootRetain(false, false);
}
ALWAYS_INLINE id
objc_object::rootRetain(bool tryRetain, bool handleOverflow)
{
if (isTaggedPointer()) return (id)this;
bool sideTableLocked = false;
bool transcribeToSideTable = false;
//extra_rc
//
isa_t oldisa;
isa_t newisa;
do {
transcribeToSideTable = false;
oldisa = LoadExclusive(&isa.bits);
newisa = oldisa;
//判断是否为nonpointer_isa
if (slowpath(!newisa.nonpointer)) { //不是nonpointer_isa 直接操作散列表
ClearExclusive(&isa.bits);
if (rawISA()->isMetaClass()) return (id)this;
if (!tryRetain && sideTableLocked) sidetable_unlock();
if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
else return sidetable_retain();
}
// don't check newisa.fast_rr; we already called any RR overrides
// 是否正在析构中..
if (slowpath(tryRetain && newisa.deallocating)) {
ClearExclusive(&isa.bits);
if (!tryRetain && sideTableLocked) sidetable_unlock();
return nil;
}
//正常情况
uintptr_t carry;
newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry); // extra_rc++
if (slowpath(carry)) {
// newisa.extra_rc++ overflowed
if (!handleOverflow) {
ClearExclusive(&isa.bits);
return rootRetain_overflow(tryRetain);
}
//当isa.extra_rc 满了,将isa.has_sidetable_rc 标记为true,
//isa.extra_rc保留数据的一半RC_HALF,另一半存入散列表中sidetable->refconts->this
// Leave half of the retain counts inline and
// prepare to copy the other half to the side table.
if (!tryRetain && !sideTableLocked) sidetable_lock();
sideTableLocked = true;
transcribeToSideTable = true;
newisa.extra_rc = RC_HALF;
newisa.has_sidetable_rc = true;
}
} while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));
if (slowpath(transcribeToSideTable)) {
// Copy the other half of the retain counts to the side table.
sidetable_addExtraRC_nolock(RC_HALF);
}
if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock();
return (id)this;
}
最终retain
会来到objc_object::rootRetain()
函数,这里可以看到一段核心的代码是在一个do while
循环中。大致分为3个部分:
- 判断当前对象是否为
nonpointer_isa
类型,如果不是,直接操作散列表
id
objc_object::sidetable_retain()
{
#if SUPPORT_NONPOINTER_ISA
ASSERT(!isa.nonpointer);
#endif
SideTable& table = SideTables()[this];
table.lock();
size_t& refcntStorage = table.refcnts[this];
if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
refcntStorage += SIDE_TABLE_RC_ONE;
}
table.unlock();
return (id)this;
}
根据this
找到对应的SideTable
,并通过table.refcnts[this]
找到当前对象的引用计数值refcntStorage
,并进行refcntStorage += SIDE_TABLE_RC_ONE;
并返回。
判断当前对象是否正在析构
即判断newisa.deallocating
是否为true
,如果正在析构(正在dealloc
),直接返回nil。正常的引用计数情况
如果以上2个if
都不满足,也就是开始正常的操作流程。首先,通过addc(newisa.bits, RC_ONE, 0, &carry)
对isa.extra_rc++
,这里用一个carry
来标记extra_rc
是否已经满了,如果数据溢出,将isa.extra_rc
的值设置为原来的一半,并将has_sidetable_rc
标识设置为true
,并将剩下的一半数据,通过
sidetable_addExtraRC_nolock(RC_HALF);
存入散列表中:
bool
objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
{
ASSERT(isa.nonpointer);
SideTable& table = SideTables()[this];
size_t& refcntStorage = table.refcnts[this];
size_t oldRefcnt = refcntStorage;
// isa-side bits should not be set here
ASSERT((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
ASSERT((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
//pinned
if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
uintptr_t carry;
size_t newRefcnt =
addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
if (carry) {
refcntStorage =
SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
return true;
}
else {
refcntStorage = newRefcnt;
return false;
}
}
这里将extra_rc
设置为原来的一半(RC_HALF),同时将另一半存入SideTable
,这里其实也是一种优化方式,当要溢出时,给extra_rc
释放容量,将释放出的内容存入Sidetable
,下次retain
直接通过extra_rc++
,减少了对SideTable
的频繁操作,通过直接操作extra_rc++
效率更高。
这就是整个retain
的流程了,首先先判断当前对象是否为nopointer
类型,如果不是,直接操作SideTable
散列表,存储引用计数,并return
;判断当前对象是否正在析构,如果正在析构,则直接return nil
;否则进入正常的引用计数处理,即isa.extra_rc++
, 判断当前extra_rc
是否溢出,如果没有直接return
; 如果发生溢出,则将extra_rc
赋值为原来的一半,并将has_sideTable_rc
标记为true
,将另一半数据存入SideTable
散列表中。
release
上面已经熟悉了retain
的流程,再看release
就比较容易了,逆向思维:
ALWAYS_INLINE bool
objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
{
if (isTaggedPointer()) return false;
bool sideTableLocked = false;
isa_t oldisa;
isa_t newisa;
retry:
do {
oldisa = LoadExclusive(&isa.bits);
newisa = oldisa;
if (slowpath(!newisa.nonpointer)) {
ClearExclusive(&isa.bits);
if (rawISA()->isMetaClass()) return false;
if (sideTableLocked) sidetable_unlock();
return sidetable_release(performDealloc);
}
// don't check newisa.fast_rr; we already called any RR overrides
uintptr_t carry;
newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry); // extra_rc--
if (slowpath(carry)) {
// don't ClearExclusive()
goto underflow;
}
} while (slowpath(!StoreReleaseExclusive(&isa.bits,
oldisa.bits, newisa.bits)));
if (slowpath(sideTableLocked)) sidetable_unlock();
return false;
underflow:
// newisa.extra_rc-- underflowed: borrow from side table or deallocate
// abandon newisa to undo the decrement
newisa = oldisa;
if (slowpath(newisa.has_sidetable_rc)) {
if (!handleUnderflow) {
ClearExclusive(&isa.bits);
return rootRelease_underflow(performDealloc);
}
// Transfer retain count from side table to inline storage.
if (!sideTableLocked) {
ClearExclusive(&isa.bits);
sidetable_lock();
sideTableLocked = true;
// Need to start over to avoid a race against
// the nonpointer -> raw pointer transition.
goto retry;
}
// Try to remove some retain counts from the side table.
size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);
// To avoid races, has_sidetable_rc must remain set
// even if the side table count is now zero.
if (borrowed > 0) {
// Side table retain count decreased.
// Try to add them to the inline count.
newisa.extra_rc = borrowed - 1; // redo the original decrement too
bool stored = StoreReleaseExclusive(&isa.bits,
oldisa.bits, newisa.bits);
if (!stored) {
// Inline update failed.
// Try it again right now. This prevents livelock on LL/SC
// architectures where the side table access itself may have
// dropped the reservation.
isa_t oldisa2 = LoadExclusive(&isa.bits);
isa_t newisa2 = oldisa2;
if (newisa2.nonpointer) {
uintptr_t overflow;
newisa2.bits =
addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow);
if (!overflow) {
stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits,
newisa2.bits);
}
}
}
if (!stored) {
// Inline update failed.
// Put the retains back in the side table.
sidetable_addExtraRC_nolock(borrowed);
goto retry;
}
// Decrement successful after borrowing from side table.
// This decrement cannot be the deallocating decrement - the side
// table lock and has_sidetable_rc bit ensure that if everyone
// else tried to -release while we worked, the last one would block.
sidetable_unlock();
return false;
}
else {
// Side table is empty after all. Fall-through to the dealloc path.
}
}
// Really deallocate.
if (slowpath(newisa.deallocating)) {
ClearExclusive(&isa.bits);
if (sideTableLocked) sidetable_unlock();
return overrelease_error();
// does not actually return
}
newisa.deallocating = true;
if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
if (slowpath(sideTableLocked)) sidetable_unlock();
__c11_atomic_thread_fence(__ATOMIC_ACQUIRE);
if (performDealloc) {
((void(*)(objc_object *, SEL))objc_msgSend)(this, @selector(dealloc));
}
return true;
}
这里还是跟retain
差不多,先是判断当前对象是否为nonpointer
类型,如果是,直接操作SideTable
操作引用计数减减:
uintptr_t
objc_object::sidetable_release(bool performDealloc)
{
#if SUPPORT_NONPOINTER_ISA
ASSERT(!isa.nonpointer);
#endif
SideTable& table = SideTables()[this];
bool do_dealloc = false;
table.lock();
auto it = table.refcnts.try_emplace(this, SIDE_TABLE_DEALLOCATING);
auto &refcnt = it.first->second;
if (it.second) {
do_dealloc = true;
} else if (refcnt < SIDE_TABLE_DEALLOCATING) {
// SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it.
do_dealloc = true;
refcnt |= SIDE_TABLE_DEALLOCATING;
} else if (! (refcnt & SIDE_TABLE_RC_PINNED)) {
refcnt -= SIDE_TABLE_RC_ONE;
}
table.unlock();
if (do_dealloc && performDealloc) {
((void(*)(objc_object *, SEL))objc_msgSend)(this, @selector(dealloc));
}
return do_dealloc;
}
如果是nonpointer
类型,直接执行extra_rc--
,之后通过carry
判断extra_rc
是否已经减没了,如果已经没值了,跳转到underflow
处理。在underflow
中,
判断是否引用散列表计数newisa.has_sidetable_rc?
,如果成立,通过size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF)
,取出对应的计数值,判断borrowed
是否大于0,如果大于0,将borrowed-1
赋值给isa.extra_rc
;如果不大于0,什么都不做。如果最终的引用计数=0 ,则会通过objc_msgSend()
触发dealloc
。
((void(*)(objc_object *, SEL))objc_msgSend)(this, @selector(dealloc));
紧接着,看dealloc
dealloc
dealloc
最终也会来到rootDealloc
inline void
objc_object::rootDealloc()
{
if (isTaggedPointer()) return; // fixme necessary?
if (fastpath(isa.nonpointer &&
!isa.weakly_referenced &&
!isa.has_assoc &&
!isa.has_cxx_dtor &&
!isa.has_sidetable_rc))
{
assert(!sidetable_present());
free(this);
}
else {
object_dispose((id)this);
}
}
首先判断当前对象是否为nonpointer
类型,且没有弱引用,没有关联对象,没有C++
函数,没有sidetable
引用,如果成立就直接free(this)
;否则object_dispose((id)this);
id
object_dispose(id obj)
{
if (!obj) return nil;
objc_destructInstance(obj);
free(obj);
return nil;
}
//释放C++相关, 移除关联对象
void *objc_destructInstance(id obj)
{
if (obj) {
// Read all of the flags at once for performance.
bool cxx = obj->hasCxxDtor();
bool assoc = obj->hasAssociatedObjects();
// This order is important.
if (cxx) object_cxxDestruct(obj);
if (assoc) _object_remove_assocations(obj);
obj->clearDeallocating();
}
return obj;
}
inline void
objc_object::clearDeallocating()
{
if (slowpath(!isa.nonpointer)) {
// Slow path for raw pointer isa.
sidetable_clearDeallocating();
}
else if (slowpath(isa.weakly_referenced || isa.has_sidetable_rc)) {
// Slow path for non-pointer isa with weak refs and/or side table data.
clearDeallocating_slow();
}
assert(!sidetable_present());
}
//清空弱引用表和引用计数表中的数据
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();
}
这里就不细说每一个函数的内容了,总之就是释放C++相关内容,移除关联对象,清空弱引用表对应的数据,清空引用计数表中对应的数据,最后执行free(this)
。
retainCount
先来一段代码:
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSObject *obj = [NSObject alloc];
NSLog(@"retainCount == %ld",CFGetRetainCount((__bridge CFTypeRef)(obj)));
NSLog(@"retainCount == %ld",CFGetRetainCount((__bridge CFTypeRef)(obj)));
NSLog(@"retainCount == %ld",CFGetRetainCount((__bridge CFTypeRef)(obj)));
}
return 0;
}
上面的retainCount
输出为多少? 答案为1,
[49975:21037772] retainCount == 1
[49975:21037772] retainCount == 1
[49975:21037772] retainCount == 1
这里只是创建对象,还没有被引用为什么就是1了呐?来看下retainCount
源码:
inline uintptr_t
objc_object::rootRetainCount()
{
if (isTaggedPointer()) return (uintptr_t)this;
sidetable_lock();
isa_t bits = LoadExclusive(&isa.bits);
ClearExclusive(&isa.bits);
if (bits.nonpointer) {
uintptr_t rc = 1 + bits.extra_rc; // alloc 1 + 0 = 1;
if (bits.has_sidetable_rc) {
rc += sidetable_getExtraRC_nolock();
}
sidetable_unlock();
return rc;
}
sidetable_unlock();
return sidetable_retainCount();
}
这里可以看到,rc = 1 + bits.extra_rc
,我们知道在alloc
内部并没有对extra_rc
做任何操作,所有这里的extra_rc = 0
,最终rc = 1
。这里也就说明,一个对象创建后,默认的引用计数为1。这里的1
其实也是有意义的,当对象创建时,第一个引用该对象的其实就是这个作用域空间,只是这个1,并没有通过extra_rc
来维护。
到此,alloc -> retain -> release -> dealloc一个闭环就形成了。
总结
关于内存管理,其实只要知道了isa.extra_rc
和has_sidetable_rc
,再结合SideTable
数据结构关系表,就可以很清楚的理解整个流程了。从头到尾梳理一遍,希望对你的工作和面试会有帮助。