我們平常開發(fā)中,我們在創(chuàng)建對象時,一般都是用這樣:
LPPerson *obj1 = [[LPPerson alloc]init];
LPPerson *obj2 = [LPPerson new];
那大家有想過,為什么必須要這樣創(chuàng)建才行?alloc和init以及new到底干了什么?今天我們就來探索下
一、準(zhǔn)備工作
1、源碼準(zhǔn)備
- 為了保證我們順利學(xué)習(xí),請先準(zhǔn)備一份最新的Objc源碼
- 配置下,保證其可以正常編譯。具體流程可以百度,很多。
2 、編譯源碼方式
-
添加符號斷點(
symbol BreakPoint)
點擊添加斷點并選擇如下:

然后添加對應(yīng)的斷點內(nèi)容:

-
按壓Control并點擊Setp in

-
使用匯編源碼
在Xcode上方的Debug菜單欄中點擊如下選項:

然后就會出現(xiàn)如下匯編界面:

二、探索alloc
我新建了一個LPPerson類,并在Viewcontroller中進(jìn)行了創(chuàng)建工作,具體代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
LPPerson *person = [LPPerson alloc];
LPPerson *person1 = [person init];
LPPerson *person2 = [person init];
NSLog(@"%@--%p--%p",person,person,&person);
NSLog(@"%@--%p--%p",person1,person1,&person1);
NSLog(@"%@--%p--%p",person2,person2,&person2);
}
我們看下運行結(jié)果:
<LPPerson: 0x600001844b60>--0x600001844b60--0x7ffee5f8c168
<LPPerson: 0x600001844b60>--0x600001844b60--0x7ffee5f8c160
<LPPerson: 0x600001844b60>--0x600001844b60--0x7ffee5f8c158
從上面的結(jié)果我們可以得到一個信息:
上面三個對象的內(nèi)存空間是同一個,所以其內(nèi)容和指針地址是相同的,但是其對象的內(nèi)存地址是不一樣的
那是不是我們可以得到結(jié)論---alloc實際上就是為對象分配內(nèi)存空間的呢?
接下來我們結(jié)合源碼來驗證下:
- 在源碼中搜索
alloc {
+ (id)alloc {
return _objc_rootAlloc(self);
}
- 再進(jìn)入
_objc_rootAlloc:
// 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*/);
}
- 再進(jìn)入
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 __OBJC2__
if (slowpath(checkNil && !cls)) return nil;
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// No shortcuts available.
if (allocWithZone) {
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
這里就發(fā)現(xiàn)代碼不是很簡單了,根據(jù)斷點我們知道接下里會走_objc_rootAllocWithZone
slowpath & fastpath
這兩個宏,在源碼中定義如下:
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
其中的__builtin_expect指令是由gcc引入的,
1、目的:編譯器可以對代碼進(jìn)行優(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 里面語句的機會更大
cls->ISA()->hasCustomAWZ()
其中fastpath中的 cls->ISA()->hasCustomAWZ()表示判斷一個類是否有自定義的 +allocWithZone實現(xiàn),這里通過斷點調(diào)試,是沒有自定義的實現(xiàn),所以會執(zhí)行到 if 里面的代碼,即走到_objc_rootAllocWithZone
- 進(jìn)入
_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);
}
- 進(jìn)入
_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());
// 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;
// 1:要開辟多少內(nèi)存
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
// 2;怎么去申請內(nèi)存
obj = (id)calloc(1, size);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
// 3: 將 cls類 與 obj指針(即isa) 關(guān)聯(lián)
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);
}
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
}
zone這種方式已經(jīng)被廢棄了,所以會直接走calloc函數(shù)
_class_createInstanceFromZone這部分是alloc源碼的核心操作,我們可以看到,其中非常關(guān)鍵的三個步驟:
-
cls->instanceSize:計算開辟內(nèi)存空間 -
calloc:申請內(nèi)存 -
obj->initInstanceIsa:將 cls類 與 obj指針(即isa) 關(guān)聯(lián)
1.instanceSize:計算開辟內(nèi)存空間
進(jìn)入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;
}
通過斷點知道接下來會進(jìn)入fastInstanceSize:
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);
}
}
進(jìn)入align16內(nèi)存對齊關(guān)鍵算法:
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
1.這里為什么要進(jìn)行內(nèi)存對齊呢?
CPU 并不是以字節(jié)為單位存取數(shù)據(jù)的。CPU把內(nèi)存當(dāng)成是一塊一塊的,塊的大小可以是2,4,8,16字節(jié)大小,因此CPU在讀取內(nèi)存時是一塊一塊進(jìn)行讀取的。每次內(nèi)存存取都會產(chǎn)生一個固定的開銷,減少內(nèi)存存取次數(shù)將提升程序的性能。即我們常說的空間換時間。所以 CPU 一般會以 2/4/8/16/32 字節(jié)為單位來進(jìn)行存取操作。我們將上述這些存取單位也就是塊大小稱為(memory access granularity)內(nèi)存存取粒度。
2.那為什么要使用16字節(jié)對齊?
在一個對象中,至少包含一個isa指針,isa指針就會占據(jù)8字節(jié)的空間,除了isa,對象可能會有其他的屬性,如果沒有其它屬性,就會預(yù)留8字節(jié)的空間,如果有其它屬性會繼續(xù)增加,但是大小永遠(yuǎn)是16的倍數(shù)。
3.對齊算法解析:

2. calloc申請內(nèi)存,返回地址指針
通過instanceSize計算的內(nèi)存大小,向內(nèi)存中申請 大小 為 size的內(nèi)存,并賦值給obj,因此 obj是指向內(nèi)存地址的指針。
obj = (id)calloc(1, size);
在calloc執(zhí)行之前,obj為nil,但是calloc執(zhí)行后,obj就為非nil了

3.obj->initInstanceIsa:類與isa關(guān)聯(lián)
在執(zhí)行完initInstanceIsa后,就可以得出一個對象指針了
- 通過對
alloc源碼的分析,可以得知alloc的主要目的就是開辟內(nèi)存,而且開辟的內(nèi)存需要使用16字節(jié)對齊算法,現(xiàn)在開辟的內(nèi)存的大小基本上都是16的整數(shù)倍 - 開辟內(nèi)存的核心步驟有3步:計算大小-- 申請內(nèi)存 -- 關(guān)聯(lián)class
alloc具體流程如下:

三、探索init
init的流程就相對簡單很多,查看objc源碼可知主要分為類方法和實例方法:
- 類方法
+ (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;
}
四、探索new
同樣的,查看源碼:
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
可以看到,new和alloc init本質(zhì)上沒有區(qū)別,new = [alloc init].但是在我們的開發(fā)中,如果一個類,你重寫了init構(gòu)法,就不要使用new來創(chuàng)建了,new可能并不會執(zhí)行你重新的方法。
覺得不錯記得點贊哦!聽說看完點贊的人逢考必過,逢獎必中。?( ′???` )比心