昨天去面試腔召,和面試官談到類對(duì)象的method列表相關(guān)話題,他突然問了個(gè)問題扮惦,你覺得類的method列表是什么時(shí)候被添加到對(duì)象上去的臀蛛?他說的主要是[[AClass alloc] init]這個(gè)過程,又問我init方法是必須調(diào)的嘛崖蜜?之前對(duì)初始化這塊了解沒這么細(xì)浊仆,所以這次面試回來,就找了runtime的源碼看了一下豫领。
通過翻閱NSObject.mm這個(gè)文件抡柿,大致找到了答案。先說結(jié)論等恐,在alloc的時(shí)候就完成了初始化洲劣。對(duì)于init方法备蚓,如果只是定義NSObject的實(shí)例,不必須調(diào)用init囱稽,其他情況最好調(diào)一下郊尝。原因如下:
我們把a(bǔ)lloc過程的調(diào)用大概列在下面:
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (checkNil && !cls) return nil;
#if __OBJC2__
if (! 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 (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 (!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 (!obj) return callBadAllocHandler(cls);
return obj;
}
}
#endif
// No shortcuts available.
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
上面代碼中有一個(gè)方法obj->initInstanceIsa(cls, dtor),這個(gè)方法最終會(huì)調(diào)到下面這個(gè)方法(下面那個(gè)else分支最終也會(huì)走到這么個(gè)方法):
inline void
objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor)
{
assert(!isTaggedPointer());
if (!indexed) {
isa.cls = cls;
} else {
assert(!DisableIndexedIsa);
isa.bits = ISA_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.indexed is part of ISA_MAGIC_VALUE
isa.has_cxx_dtor = hasCxxDtor;
isa.shiftcls = (uintptr_t)cls >> 3;
}
}
在這個(gè)方法中战惊,對(duì)cls屬性進(jìn)行了賦值流昏,也就是確定了類的歸屬,并連接到了那個(gè)類样傍,所以在alloc的時(shí)候完成了cls的賦值横缔,也就是在alloc的時(shí)候就初始化完成了铺遂。
接下來再看init方法:
- (id)init {
return _objc_rootInit(self);
}
id _objc_rootInit(id obj)
{
return obj;
}
在NSObject中只是簡單返回了這個(gè)自身衫哥。所以如果你是調(diào)用別人寫的類或者自己寫的繼承自NSObject并且自己在init中做了自定義的,那肯定是要調(diào)的襟锐。