在iOS開發(fā)中了,我們每天都會使用+ alloc和- init這兩個方進行對象的初始化。我們也這知道整個對象的初始化過程其實就是開辟一塊內(nèi)存空間,并且初始化isa_t結(jié)構(gòu)體的過程。
alloc的實現(xiàn)
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls) {
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
整個過程其實就是NSObject對callAlloc方法的實現(xiàn)。
callAlloc
/*
cls:CustomClass
checkNil:是否檢查Cls
allocWithZone:是否分配到指定空間,默認為false,內(nèi)部會對其進行優(yōu)化
*/
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false) {
//沒有class或則checkNil為YES,返回空
if (slowpath(checkNil && !cls)) return nil;
//確保只有Objective-C 2.0語言的文件所引用
#if __OBJC2__
//判斷class有沒有默認的allocWithZone方法
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
// class可以快速分配
if (fastpath(cls->canAllocFast())) {
//hasCxxDtor();是C++析構(gòu)函數(shù),判斷是否有析構(gòu)函數(shù)
bool dtor = cls->hasCxxDtor();
//申請class的內(nèi)存空間
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
if (slowpath(!obj)) return callBadAllocHandler(cls);
//初始化isa指針
obj->initInstanceIsa(cls, dtor);
return obj;
}
else {
//使用class_createInstance創(chuàng)建class
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
}
#endif
//說明有默認的allocWithZone的方法,調(diào)用allocWithZone方法
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
在__OBJC2__下當前類有沒有默認的allocWithZone方法是通過hasCustomAWZ()函數(shù)判斷的。YES代表有則會調(diào)用[cls allocWithZone:nil]方法。NO代表沒有,這時候會根據(jù)當前類是否可以快速分配,NO的話調(diào)用class_createInstance函數(shù);YES則分配內(nèi)存并初始化isa。
allocWithZone
+ (id)allocWithZone:(struct _NSZone *)zone {
return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}
id _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone) {
id obj;
#if __OBJC2__
// allocWithZone under __OBJC2__ ignores the zone parameter
(void)zone;
obj = class_createInstance(cls, 0);
#else
if (!zone) {
obj = class_createInstance(cls, 0);
}
else {
obj = class_createInstanceFromZone(cls, 0, zone);
}
#endif
if (slowpath(!obj)) obj = callBadAllocHandler(cls);
return obj;
}
allocWithZone函數(shù)的本質(zhì)是調(diào)用_objc_rootAllocWithZone函數(shù)。
_objc_rootAllocWithZone的邏輯分為兩種情況:
- 先判斷是否是
__OBJC2__,如果是則調(diào)用class_createInstance; - 判斷
zone是否為空,如果為空調(diào)用class_createInstance,如果不為空,調(diào)用class_createInstanceFromZone。
//class_createInstance
id class_createInstance(Class cls, size_t extraBytes) {
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
//class_createInstanceFromZone
id class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone) {
return _class_createInstanceFromZone(cls, extraBytes, zone);
}
class_createInstance和class_createInstanceFromZone的本質(zhì)都是調(diào)用_class_createInstanceFromZone。
另外通過前面的源代碼我們可以發(fā)現(xiàn):用alloc方式創(chuàng)建,只要當前類有allocWithZone方法,最終一定是調(diào)用class_createInstance。
_class_createInstanceFromZone
static __attribute__((always_inline))
id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil) {
if (!cls) return nil;
assert(cls->isRealized());
bool hasCxxCtor = cls->hasCxxCtor();//構(gòu)造函數(shù)
bool hasCxxDtor = cls->hasCxxDtor();//析構(gòu)函數(shù)
bool fast = cls->canAllocNonpointer(); //是對isa的類型的區(qū)分,如果一個類不能使用isa_t類型的isa的話,fast就為false,但是在Objective-C 2.0中,大部分類都是支持的
//在分配內(nèi)存之前,需要知道對象在內(nèi)存中的大小,也就是instanceSize的作用。對象必須大于等于16字節(jié)。
size_t size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (!zone && fast) {
//分配內(nèi)存空間
obj = (id)calloc(1, size);
if (!obj) return nil;
//初始化isa指針
obj->initInstanceIsa(cls, hasCxxDtor);
} else {
//此時的fast 為 false
//在C語言中,malloc表示在內(nèi)存的動態(tài)存儲區(qū)中分配一塊長度為“size”字節(jié)的連續(xù)區(qū)域,返回該區(qū)域的首地址;calloc表示在內(nèi)存的動態(tài)存儲區(qū)中分配n塊長度為“size”字節(jié)的連續(xù)區(qū)域,返回首地址。
if (zone) {
obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
if (!obj) return nil;
//初始化isa指針
obj->initIsa(cls);
}
if (cxxConstruct && hasCxxCtor) {
obj = _objc_constructOrFree(obj, cls);
}
return obj;
}
初始化isa
_class_createInstanceFromZone中不光開辟了內(nèi)存空間,還初始化了isa。初始化isa的方法有initInstanceIsa和initIsa,但是本質(zhì)都是調(diào)用initIsa(Class cls, bool nonpointer, bool hasCxxDtor)。
inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
{
assert(!isTaggedPointer());
if (!nonpointer) {
isa.cls = cls; //obj->initIsa(cls)
} else {
//obj->initInstanceIsa(cls, hasCxxDtor);
assert(!DisableNonpointerIsa);
assert(!cls->instancesRequireRawIsa());
isa_t newisa(0);
#if SUPPORT_INDEXED_ISA
assert(cls->classArrayIndex() > 0);
newisa.bits = ISA_INDEX_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
newisa.bits = ISA_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
// This write must be performed in a single store in some cases
// (for example when realizing a class because other threads
// may simultaneously try to use the class).
// fixme use atomics here to guarantee single-store and to
// guarantee memory order w.r.t. the class index table
// ...but not too atomic because we don't want to hurt instantiation
isa = newisa;
}
}
根據(jù)《OC引用計數(shù)器的原理》,現(xiàn)在再看一下初始化isa的方法。這個方法的意思是首先判斷是否開啟指針優(yōu)化。
沒有開啟指針優(yōu)化的話訪問 objc_object的isa會直接返回isa_t結(jié)構(gòu)中的cls變量,cls變量會指向?qū)ο笏鶎俚念惖慕Y(jié)構(gòu)。
開啟指針優(yōu)化的話通過newisa(0)函數(shù)初始化一個isa,并根據(jù)SUPPORT_INDEXED_ISA分別設(shè)置對應(yīng)的值。iOS設(shè)備的話這個值是0,所以執(zhí)行else的代碼。

這里可能會有個疑問,既然alloc將分配內(nèi)存空間和初始化isa的事情都做了,那么init的作用是什么呢?
init
- (id)init {
return _objc_rootInit(self);
}
id _objc_rootInit(id obj) {
return obj;
}
init的作用就是返回當前對象。這里有個問題既然init只是返回當前對象,為什么要多此一舉呢?
Apple給出的注釋:
In practice, it will be hard to rely on this function. Many classes do not properly chain -init calls.
意思是在實踐中,很難依靠這個功能。許多類沒有正確鏈接init調(diào)用。所以這個函數(shù)很可能不被調(diào)用。也許是歷史遺留問題吧。
new
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
所以說UIView *view = [UIView new];和UIView *view = [[UIView alloc]init];是一樣的。
dealloc
分析了對象的生成,我們現(xiàn)在看一下對象是如何被銷毀的。dealloc的實現(xiàn)如下:
- (void)dealloc {
_objc_rootDealloc(self);
}
void _objc_rootDealloc(id obj) {
assert(obj);
obj->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);
}
}
rootDealloc分為三種情況:
- 如果是TaggedPointer,直接return;
- 進行一些關(guān)于isa的條件判斷,如果滿足就釋放分配的內(nèi)存控件;
- 調(diào)用
object_dispose函數(shù),這是最重要的;
objc_destructInstance
我們先看object_dispose函數(shù)的源碼:
id object_dispose(id obj) {
if (!obj) return nil;
objc_destructInstance(obj);
free(obj);
return nil;
}
做了兩件事情:
- 調(diào)用
objc_destructInstance函數(shù) - 釋放分配的內(nèi)存空間
objc_destructInstance的實現(xiàn)如下:
/***********************************************************************
* objc_destructInstance
* Destroys an instance without freeing memory.
* Calls C++ destructors.
* Calls ARC ivar cleanup.
* Removes associative references.
* Returns `obj`. Does nothing if `obj` is nil.
**********************************************************************/
void *objc_destructInstance(id obj)
{
if (obj) {
// Read all of the flags at once for performance.
bool cxx = obj->hasCxxDtor();//是否有析構(gòu)函數(shù)
bool assoc = obj->hasAssociatedObjects();//是否有關(guān)聯(lián)對象
// This order is important.
if (cxx) object_cxxDestruct(obj);//調(diào)用析構(gòu)函數(shù)
if (assoc) _object_remove_assocations(obj);//刪除關(guān)聯(lián)對象
obj->clearDeallocating();//清空引用計數(shù)表并清除弱引用表
}
return obj;
}
objc_destructInstance做了三件事情:
- 執(zhí)行
object_cxxDestruct調(diào)用析構(gòu)函數(shù) - 執(zhí)行
_object_remove_assocations刪除關(guān)聯(lián)對象 - 執(zhí)行
clearDeallocating清空引用計數(shù)表并清除弱引用表,將所有weak引用指nil(這也解釋了為什么使用weak能自動置空)
object_cxxDestruct
在源碼中object_cxxDestruct的實現(xiàn)由object_cxxDestructFromClass完成。
static void object_cxxDestructFromClass(id obj, Class cls)
{
void (*dtor)(id);
// Call cls's dtor first, then superclasses's dtors.
for ( ; cls; cls = cls->superclass) {
if (!cls->hasCxxDtor()) return;
dtor = (void(*)(id))
lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
if (dtor != (void(*)(id))_objc_msgForward_impcache) {
if (PrintCxxCtors) {
_objc_inform("CXX: calling C++ destructors for class %s",
cls->nameForLogging());
}
(*dtor)(obj);
}
}
}
這段代碼的意思就是沿著繼承鏈逐層向上搜尋SEL_cxx_destruct這個selector,找到函數(shù)實現(xiàn)(void (*)(id)(函數(shù)指針)并執(zhí)行。說白了就是找析構(gòu)函數(shù),并執(zhí)行析構(gòu)函數(shù)。
析構(gòu)函數(shù)中書如何處理成員變量的?
- 對于strong來說執(zhí)行
objc_storeStrong(&ivar, nil)release舊對象,ivar賦新值nil; - 對于weak來說執(zhí)行
objc_destroyWeak(&ivar)消除對象weak表中的ivar地址。
關(guān)于這個函數(shù)Sunnyxx ARC下dealloc過程及.cxx_destruct的探究中也有提到。
用一張圖表示dealloc的流程:

至于dealloc的調(diào)用時機,是跟引用計數(shù)器相關(guān)的。