??我們先看代碼,這些代碼輸出了什么,代表了什么意思,輸出的內(nèi)容是否相同?
HKPerson *p1 = [HKPerson alloc];
HKPerson *p2 = [p1 init];
HKPerson *p3 = [p1 init];
HKNSLog(@"%@ - %p - %p",p1,p1,&p1);
HKNSLog(@"%@ - %p - %p",p2,p2,&p2);
HKNSLog(@"%@ - %p - %p",p3,p3,&p3);
??輸出內(nèi)容:

??通過輸出結(jié)果,我們可以知道前兩個內(nèi)容相同,跟后面的
&p1結(jié)果不相同,所以我們知道init并不會修改對象的內(nèi)存空間。所以p1,p2,p3指向的是同一片內(nèi)存空間。只是指針不通,所以&p不同??聪聢D:
查看源碼下載 objc4-781
alloc流程分析:

①根據(jù)main函數(shù)中的alloc方法進入源碼實現(xiàn)
+ (id)alloc {
return _objc_rootAlloc(self);
}
②進入_objc_rootAlloc方法
id _Nullable
_objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
③進入callAlloc方法
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__ //有可用的編譯器優(yōu)化
// checkNil 為false,!cls 也為false ,所以slowpath 為 false,假值判斷不會走到if里面,即不會返回nil
if (slowpath(checkNil && !cls)) return nil;
//判斷一個類是否有自定義的 +allocWithZone 實現(xiàn),沒有則走到if里面的實現(xiàn)
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// No shortcuts available. // 沒有可用的編譯器優(yōu)化
if (allocWithZone) {
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
??我們通過符號斷點知道程序走到了這個方法_objc_rootAllocWithZone。
slowpath & fastpath
??其中關(guān)于slowpath和fastpath這兩個都是objc源碼中定義的宏,其定義如下
//x很可能為真, fastpath 可以簡稱為 真值判斷
#define fastpath(x) (__builtin_expect(bool(x), 1))
//x很可能為假,slowpath 可以簡稱為 假值判斷
#define slowpath(x) (__builtin_expect(bool(x), 0))
其中的__builtin_expect指令是由gcc引入的,
1、目的:編譯器可以對代碼進行優(yōu)化,以減少指令跳轉(zhuǎn)帶來的性能下降。即性能優(yōu)化
2、作用:允許程序員將最有可能執(zhí)行的分支告訴編譯器。
3、指令的寫法為:__builtin_expect(EXP, N)。表示EXP==N的概率很大。
4、fastpath定義中__builtin_expect((x),1)表示x的值為真的可能性更大;即 執(zhí)行if里面語句的機會更大
5、slowpath定義中的__builtin_expect((x),0)表示x的值為假的可能性更大。即執(zhí)行else里面語句的機會更大
6、在日常的開發(fā)中,也可以通過設(shè)置來優(yōu)化編譯器,達到性能優(yōu)化的目的,設(shè)置的路徑為:Build Setting --> Optimization Level --> Debug --> 將None改為fastest或者smallest
④進入_objc_rootAllocWithZone方法
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
// allocWithZone under __OBJC2__ ignores the zone parameter
//zone 參數(shù)不再使用 類創(chuàng)建實例內(nèi)存空間
return _class_createInstanceFromZone(cls, 0, nil,
OBJECT_CONSTRUCT_CALL_BADALLOC);
}
⑤進入_class_createInstanceFromZone方法
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
int construct_flags = OBJECT_CONSTRUCT_NONE,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
ASSERT(cls->isRealized()); //檢查是否已經(jīng)實現(xiàn)
// Read class's info bits all at once for performance
//一次性讀取類的位信息以提高性能
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size;
//計算需要開辟的內(nèi)存大小,傳入的extraBytes 為 0
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
//申請內(nèi)存
obj = (id)calloc(1, size);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
if (!zone && fast) {
//將 cls類 與 obj指針(即isa) 關(guān)聯(lián)
obj->initInstanceIsa(cls, hasCxxDtor);
} else {
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
if (fastpath(!hasCxxCtor)) {
return obj;
}
construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
return object_cxxConstructFromClass(obj, cls, construct_flags);
}
??這里有三個方法很重要
cls->instanceSize
calloc
initInstanceIsa
如下圖:

instanceSize
size_t instanceSize(size_t extraBytes) const {
if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
return cache.fastInstanceSize(extraBytes);
}
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;
return size;
}
這里有一個內(nèi)存對齊的概念,即如果申請的內(nèi)存小于16就取16。算法如下:
//16字節(jié)對齊算法
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
calloc
??通過instanceSize計算的內(nèi)存大小,向內(nèi)存中申請 大小 為size的內(nèi)存,并賦值給obj,因此obj是指向內(nèi)存地址的指針。
obj = (id)calloc(1, size);
??這里我們可以通過斷點來印證上述的說法,在未執(zhí)行calloc時,po obj為nil,執(zhí)行后,再po obj法線,返回了一個16進制的地址。

在平常的開發(fā)中,一般一個對象的打印的格式都是類似于這樣的<HKPerson: 0x01111111f>(是一個指針)。為什么這里不是呢?
1.主要是因為
objc地址 還沒有與傳入的cls進行關(guān)聯(lián),2.同時印證了
alloc的根本作用就是 開辟內(nèi)存
obj->initInstanceIsa:類與isa關(guān)聯(lián)
主要過程就是初始化一個isa指針,并將isa指針指向申請的內(nèi)存地址,在將指針與cls類進行關(guān)聯(lián)。
總結(jié):
-
alloc的主要作用就是開辟內(nèi)存空間。
init 源碼探索
說完了alloc,接下來我們討論init。
+ (id)init {
return (id)self;
}
??這里的init是一個構(gòu)造方法 ,是通過工廠設(shè)計(工廠方法模式),主要是用于給用戶提供構(gòu)造方法入口。這里能使用id強轉(zhuǎn)的原因,主要還是因為內(nèi)存字節(jié)對齊后,可以使用類型強轉(zhuǎn)為你所需的類型
HKPerson *objc = [[HKPerson alloc] init];
接下來我們進入方法:
- (id)init {
return _objc_rootInit(self);
}
進入_objc_rootInit
id
_objc_rootInit(id obj)
{
// In practice, it will be hard to rely on this function.
// Many classes do not properly chain -init calls.
return obj;
}
我們發(fā)現(xiàn)返回的是對象本身。
new 源碼探索
??一般在開發(fā)中,初始化除了init,還可以使用new,兩者本質(zhì)上并沒有什么區(qū)別,以下是objc中new的源碼實現(xiàn),通過源碼可以得知,new函數(shù)中直接調(diào)用了callAlloc函數(shù)(即alloc中分析的函數(shù)),且調(diào)用了init函數(shù),所以可以得出new其實就等價于 [alloc init]的結(jié)論。
但是一般開發(fā)中并不建議使用new,主要是因為有時會重寫init方法做一些自定義的操作,用new初始化可能會無法走到自定義的部分。