昨天去面试,和面试官谈到类对象的method列表相关话题,他突然问了个问题,你觉得类的method列表是什么时候被添加到对象上去的?他说的主要是[[AClass alloc] init]这个过程,又问我init方法是必须调的嘛?之前对初始化这块了解没这么细,所以这次面试回来,就找了runtime的源码看了一下。
通过翻阅NSObject.mm这个文件,大致找到了答案。先说结论,在alloc的时候就完成了初始化。对于init方法,如果只是定义NSObject的实例,不必须调用init,其他情况最好调一下。原因如下:
我们把alloc过程的调用大概列在下面:
+ (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];
}
上面代码中有一个方法obj->initInstanceIsa(cls, dtor),这个方法最终会调到下面这个方法(下面那个else分支最终也会走到这么个方法):
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;
}
}
在这个方法中,对cls属性进行了赋值,也就是确定了类的归属,并连接到了那个类,所以在alloc的时候完成了cls的赋值,也就是在alloc的时候就初始化完成了。
接下来再看init方法:
- (id)init {
return _objc_rootInit(self);
}
id _objc_rootInit(id obj)
{
return obj;
}
在NSObject中只是简单返回了这个自身。所以如果你是调用别人写的类或者自己写的继承自NSObject并且自己在init中做了自定义的,那肯定是要调的。