前言
在OC開發(fā)中最基本的就是對象的創(chuàng)建,也就是用alloc和init方法來初始化對象,但是在我們日常開發(fā)中這個對象創(chuàng)建的最基本最簡單的操作我們只知道怎么使用,并不知道里面的底層到底做了什么,這就是這篇文章的以下需要介紹的alloc底層原理。
為了更好的介紹以下的內容定義了一個TestObject的類
@interface TestObject : NSObject
@end
#import "TestObject.h"
@implementation TestObject
+ (void)initialize
{
NSLog(@"%s",__func__);
}
+(instancetype)allocWithZone:(struct _NSzone *)zone{
NSLog(@"%s",__func__);
return [super allocWithZone:zone];
}
@end
在介紹之前先來一個簡單的例子
TestObject *test = [TestObject alloc];
TestObject *test1 = [test init];
TestObject *test2 = [test1 init];
NSLog(@"=========輸出結果============");
NSLog(@"%@---%p",test,&test);
NSLog(@"%@---%p",test1,&test1);
NSLog(@"%@---%p",test2,&test2);
=========輸出結果============
2020-04-28 09:45:04.657448+0800 AllocDemo[3448:65473] <TestObject: 0x600002dfdf70>---0x7ffee4081188
2020-04-28 09:45:04.657608+0800 AllocDemo[3448:65473] <TestObject: 0x600002dfdf70>---0x7ffee4081180
2020-04-28 09:45:04.657769+0800 AllocDemo[3448:65473] <TestObject: 0x600002dfdf70>---0x7ffee4081178
從例子可以看到,這三個是同一個對象,但是指針的地址是不同的,那么問題來了,為什么這三個對象地址是一樣的?alloc和init底層到底做了什么?
1.通過匯編來對alloc的探索
1.可以在Xcode上的Debug->Debug Workflow->Always show Disassembly,如圖:
當然,這種方式是對整個項目對全局操作的,那么就在需要用到的時候,先打斷點,然后再開啟。
2.配合系統(tǒng)斷點的形式來就可以一步一步看到alloc底層的每一步的流程。通過這樣的方式可以找到alloc的底層的入口,是objc_alloc底層方法
通過系統(tǒng)的斷點,知道
objc_alloc方法是在libobjc.A.dylib的庫里面,并且它的下一步是alloc方法。
雖然這種方式可以知道底層的流程走向。但是具體的各個函數的實現是不清楚的,并且這種方式也比較麻煩不直觀。
2.源碼分析alloc底層
但是蘋果官方開源了這部分的源碼,可以在蘋果源碼列表找到objc4,在里面下載,可以配合這個大佬的配置iOS_objc4-756.2 最新源碼編譯調試讓源碼可以在Xcode上運行。接下來,我就是根據objc4-756.2的源碼來進行探索的。
2.1 alloc的入口objc_alloc
通過上面的匯編可以知道objc_alloc是alloc的底層入口,但是我們通過源碼的配置點擊進去的話是會直接跳轉到
+ (id)alloc {
return _objc_rootAlloc(self);
}
這是一個類方法,這是為什么呢?
因為第一次alloc跑到objc_alloc這種是只走一次,原因就是sel實現imp函數地址,在macho的符號綁定(綁定symbol)的sel_alloc找到可以找到objc_alloc
通過源碼可以知道其中方法
fixupMessageRef在正常的情況下不走,只有這個對象需要修復的時候才走,所以正常的情況下這個對象就是已經綁定了,所以在正常情況下打斷點是不會跑到這里的。
所以通過源碼將斷點打在objc_alloc方法上,進行下一步
2.2 callAlloc
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (slowpath(checkNil && !cls)) return nil;
#if __OBJC2__
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
// No alloc/allocWithZone implementation. Go straight to the allocator.
// fixme store hasCustomAWZ in the non-meta class and
// add it to canAllocFast's summary
if (fastpath(cls->canAllocFast())) {
// No ctors, raw isa, etc. Go straight to the metal.
bool dtor = cls->hasCxxDtor();
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
if (slowpath(!obj)) return callBadAllocHandler(cls);
obj->initInstanceIsa(cls, dtor);
return obj;
}
else {
// Has ctor or raw isa or something. Use the slower path.
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
}
#endif
// No shortcuts available.
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
第一次進來是從objc_alloc里面進來的,其中checkNil為true,allocWithZone為false,因為第一次進來fastpath(!cls->ISA()->hasCustomAWZ())中的cls還沒有指針isa,所以為false,直接return [cls alloc],其中在調用了[cls alloc]方法會會觸發(fā)objc_msgSend調用initialize類方法,因為這個方法在第一次初始化該類之前會被調用。
所以第一次的流程是最外面的alloc-->objec_alloc-->callAlloc(Class cls, true, false)
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
slowpath(bool)與fastpath(bool):常用于if-else,可以優(yōu)化判斷的速度。
應用gcc指令__builtin_expect(EXP,N) ,通過此指令優(yōu)化編譯器在編譯時的代碼布局,減少指令跳轉帶來的性能消耗。
2.3 alloc的第二次流程
通過第一次的callAlloc返回,根據斷點跳轉到了
+ (id)alloc {
return _objc_rootAlloc(self);
}
// 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*/);
}
此時會再次調用callAlloc方法,但是此時的參數checkNil為false,allocWithZone為true。因為之前調用了initialize類方法,此時的bits是有值了,直接進入到了if(fastpath(!cls->ISA()->hasCustomAWZ()))里面。
2.3.1 hasCustomAWZ()方法的解析
bool hasCustomAWZ() {
return ! bits.hasDefaultAWZ();
}
hasCustomAWZ方法意思就是判斷是否實現自定義的allocWithZone方法,如果沒有實現就調用系統(tǒng)默認的allocWithZone方法。
因為fastpath(cls->canAllocFast())根據源碼返回的永遠都是false
bool canAllocFast() {
assert(!isFuture());
return bits.canAllocFast();
}
#if FAST_ALLOC
·····
#else
····
bool canAllocFast() {
return false;
}
#endif
#define FAST_ALLOC (1UL<<2)
所以不會執(zhí)行if里面的代碼塊,只會執(zhí)行else里面的代碼塊
2.3.2 類中實現allocWithZone類方法對流程的影響
1.類沒有實現allocWithZone方法的時候是需要運行fastpath(!cls->ISA()->hasCustomAWZ())判斷里面的代碼,最終是通過class_createInstance的返回
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
所以這個的流程是:alloc->_objc_rootAlloc->callAlloc(cls,false,true)->class_createInstance->_class_createInstanceFromZone
2.類實現了allocWithZone方法的時候就不會運行fastpath(!cls->ISA()->hasCustomAWZ())判斷里面的代碼,直接跑
if (allocWithZone) return [cls allocWithZone:nil];
并且這時候會執(zhí)行類中實現的allocWithZone方法
2020-04-28 23:55:18.173680+0800 LGTest[2370:69449] +[TestObject allocWithZone:]
通過斷點的形式得到的流程是:
alloc->_objc_rootAlloc->callAlloc(cls,false,true)->allocWithZone->_objc_rootAllocWithZone->class_createInstance->_class_createInstanceFromZone
最終這兩種情況下都會執(zhí)行到_class_createInstanceFromZone這個函數里面。
2.3.4 _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());
// Read class's info bits all at once for performance
//判斷當前class或者superclass是否有.cxx_construct構造方法的實現
bool hasCxxCtor = cls->hasCxxCtor();
//判斷當前class或者superclass是否有.cxx——destruct析構方法的實現
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
//通過進行內存對齊得到實例大小
size_t size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (!zone && fast) {
obj = (id)calloc(1, size);
if (!obj) return nil;
//初始化實例的isa指針
obj->initInstanceIsa(cls, hasCxxDtor);
}
else {
if (zone) {
obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
if (!obj) return nil;
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
if (cxxConstruct && hasCxxCtor) {
obj = _objc_constructOrFree(obj, cls);
}
return obj;
}
下面是對_class_createInstanceFromZone的分析
1.cls->instanceSize(extraBytes)是進行內存對齊得到的實例大小,里面的流程分別如下:
size_t instanceSize(size_t extraBytes) {
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;
return size;
}
uint32_t alignedInstanceSize() {
return word_align(unalignedInstanceSize());
}
uint32_t unalignedInstanceSize() {
assert(isRealized());
return data()->ro->instanceSize;
}
static inline uint32_t word_align(uint32_t x) {
return (x + WORD_MASK) & ~WORD_MASK;
}
#ifdef __LP64__
# define WORD_MASK 7UL
#else
# define WORD_MASK 3UL
#endif
一開始進來的時候extraBytes為0的,因為當前的TestObject里面是沒有屬性的,是不是覺得開辟的內存空間是0呢?并不是的,因為還有一個isa
@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
Class isa OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
通過流程可以知道在unalignedInstanceSize方法中得到編譯進去的實例的大小,因為isa是一個對象指針,所以這個的大小是一個8字節(jié)。所以傳到word_align方法里面的x為8。其中WORD_MASK在64位系統(tǒng)下是7,否則是3,因此,word_align()方法在64位系統(tǒng)下進行計算是8字節(jié)對齊按照里面的算法就是相當于8的倍數。返回到instanceSize()方法中的size就是對象需要的空間大小為8,因為里面有小于16的返回16。
2.calloc函數是初始化所分配的內存空間的。
3.initInstanceIsa函數是初始化isa,關聯cls的,這部分內容后續(xù)會進行介紹。
2.4 init和new
1.介紹完alloc之后,init方法通過源碼
- (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;
}
其實就是返回它的本身的。
2.new的方法通過源碼知道是 callAlloc方法和 init的方法的結合
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
3.最后
通過上面的流程得到了最終的alloc在底層的流程圖