一. 源碼探索的三種方式
在OC中我們以alloc為例,查找alloc所在的源碼庫
1.符號斷點(diǎn)

- 選擇斷點(diǎn)
symBolic Breakpoint - 輸入
alloc添加符號斷點(diǎn) - 先將這個符號斷點(diǎn)關(guān)閉,在main 的
Person *person = [Person alloc];打斷點(diǎn),運(yùn)行. -
當(dāng)程序斷點(diǎn)在Persion部分后將符號斷點(diǎn)打開,斷點(diǎn)下一步如圖:
從下圖可以看出 alloc 的源碼位于libobjc.A.dylib庫
結(jié)果
2. control + step into
- 在main 的
Person *person = [Person alloc];打斷點(diǎn),運(yùn)行
-當(dāng)斷在alloc處時,使用control + step into進(jìn)入 如圖;
跳轉(zhuǎn)結(jié)果 - 加符號斷點(diǎn)
objc_alloc后發(fā)現(xiàn)顯示其源碼所在libobjc.A.dylib
3 .匯編查找
- 在main 的
Person *person = [Person alloc];打斷點(diǎn),運(yùn)行 - xcode 工具欄 選擇
Debug --> Debug Workflow --> Always Show Disassembly,顯示反匯編 . - 使用
control + step into進(jìn)入
結(jié)果 - 加符號斷點(diǎn)
objc_alloc后發(fā)現(xiàn)顯示其源碼所在libobjc.A.dylib
注意(以下是Apple 提供的源碼下載地址):
1、Apple 所有開源源碼匯總地址,根據(jù)相應(yīng)的版本查找對應(yīng)的源碼,以mac 10.15為例: macOS --> 10.15 --> 選擇10.15 --> 搜索 objc
2、Apple 比較直接的源碼下載地址,直接搜索想要下載的源碼名稱即可,例如objc:直接搜索 objc --> objc4/ --> 選擇相應(yīng)的objc的版本
二 alloc 流程 源碼解析
準(zhǔn)備工作: 下載 objc4-781 源碼并編譯

- 1 .根據(jù)
[Person alloc]方法進(jìn)入alloc源碼
方法跳轉(zhuǎn) [ NSObjc alloc]
+ (id)alloc {
return _objc_rootAlloc(self);
}
但當(dāng)我們運(yùn)行調(diào)試時發(fā)現(xiàn)先走的是
// Calls [cls alloc].
id
objc_alloc(Class cls)
{
return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}
這里我們先在下一篇文章中討論,涉及到LLVM優(yōu)化 也是我們創(chuàng)建的類與系統(tǒng)類如NSObject alloc方法一點(diǎn)區(qū)別
- 2
//第二層
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
-3 通過斷點(diǎn)調(diào)試發(fā)現(xiàn)走_objc_rootAllocWithZone方法
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate
// shortcutting optimizations.
static ALWAYS_INLINE id
//#define ALWAYS_INLINE inline __attribute__((always_inline))
// ALWAYS_INLINE強(qiáng)制開啟 inline inline 是一種降低函數(shù)調(diào)用成本的方法,其本質(zhì)是在調(diào)用聲明為 inline 的函數(shù)時,會直接把函數(shù)的實(shí)現(xiàn)替換過去,這樣減少了調(diào)用函數(shù)的成本。 是一種以空間換時間的做法
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
//這里會進(jìn)行 slowpath fastpath判斷
//#define fastpath(x) (__builtin_expect(bool(x), 1)) x可能為真
//#define slowpath(x) (__builtin_expect(bool(x), 0)) x很可能為假
if (slowpath(checkNil && !cls)) return nil;
if (fastpath(!cls->ISA()->hasCustomAWZ())) { //cls->ISA()->hasCustomAWZ()判斷一個類是否有自定義的 +allocWithZone 實(shí)現(xiàn) 如果有 值會存儲在metaclass中
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));
}
這里解釋下 slowpath fastpath, __builtin_expect是 GCC (version >= 2.96)提供給程序員使用的,目的是將“分支轉(zhuǎn)移”的信息提供給編譯器,即提高預(yù)讀指令的命中率 這樣編譯器可以對代碼進(jìn)行優(yōu)化,以減少指令跳轉(zhuǎn)帶來的性能下降
int x, y;
if((fastpath (x > 0)) //在x的值大于0 的概率比較小的情況下可以使用,編譯器可以預(yù)先讀取y = 1這條指令,減少重新取指
y = 1;
else
y = 0;
__builtin_expect(EXP, N)。表示 EXP==N的概率很大。if(fastpath(value)) //等價于 if(value)
xode中可以通過:Build Setting --> Optimization Level --> Debug --> 將None 改為 fastest 或者 smallest 來設(shè)置是否啟用優(yōu)化編輯器
4 _objc_rootAllocWithZone
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
// allocWithZone under __OBJC2__ ignores the zone parameter
return _class_createInstanceFromZone(cls, 0, nil,
OBJECT_CONSTRUCT_CALL_BADALLOC);
}
- 5 _class_createInstanceFromZone
/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* Note: this function has been carefully written so that the fastpath
* takes no branch.
**********************************************************************/
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());
// 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;
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
// alloc 開辟內(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) {
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);
}
這里我們查看下三個重點(diǎn)方法
- 5.1
size = cls->instanceSize(extraBytes);計算創(chuàng)建此對象所需開辟空間大小
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;
}
size_t fastInstanceSize(size_t extra) const
{
ASSERT(hasFastInstanceSize(extra));
if (__builtin_constant_p(extra) && extra == 0) {
return _flags & FAST_CACHE_ALLOC_MASK16;
} else {
size_t size = _flags & FAST_CACHE_ALLOC_MASK;
// remove the FAST_CACHE_ALLOC_DELTA16 that was added
// by setFastInstanceSize
return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
}
}
//16 進(jìn)制字節(jié)對齊算法
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
以align16(8)為例 返回 8 + 15 = 23 -> 0000 0000 0001 0111
15 -> 0000 0000 0000 1111 取反為 1111 1111 1111 0000
&運(yùn)算得 0000 0000 0001 0000 = 16
&運(yùn)算 每位都為1 結(jié)果為1 反之為0
字節(jié)對齊原因
為提高CPU性能 CPU存取數(shù)據(jù)是以內(nèi)存塊為單位 ,例如一個無屬性的對象 默認(rèn)isa指針占8個字節(jié)字節(jié)對齊后預(yù)留8個字節(jié), 因為內(nèi)存是連續(xù)的 所以會與后一個對象isa指針有8字節(jié)距離,防止造成訪問混亂. 64位系統(tǒng)中
5.2
obj = (id)calloc(1, size);
將上一步計算出的內(nèi)存大小傳給calloc方法,開辟一個相應(yīng)大小的內(nèi)存空間,如果有斷點(diǎn)走到這一步,calloc執(zhí)行后 obj已經(jīng)有值為一個16位地址,但沒有對象標(biāo)識例如<Person: 0x01111111f>
-5.3 obj->initInstanceIsa(cls, hasCxxDtor);
類與地址關(guān)聯(lián) return obj;
三 init
+ (id)init {
return (id)self;
}
- (id)init {
return _objc_rootInit(self);
}
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;
}
這個就比較簡單了 直接返回self
四 new
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
由源碼可以看出相當(dāng)于 alloc init,但使用new方法無法調(diào)用 重寫的init方法如initWIthName:...所以一般不推薦使用



