直接查看源碼
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
//[[self alloc] init]
}
從上面可知,兩種方法都走的是callAlloc
,只是前者傳的第三個(gè)參數(shù)是true,后者沒有傳(即可能存在默認(rèn)值)知给。
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];
}
根據(jù)callAlloc的實(shí)現(xiàn),可以看到第三個(gè)參數(shù)默認(rèn)是false,而縱觀整個(gè)實(shí)現(xiàn)方法涩赢,只有最后兩行代碼用到了第三個(gè)參數(shù)戈次。
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
可以看到allocWithZone為false的情況下,又回到了alloc方法筒扒。
總結(jié)
[[NSObject alloc] init]與[NSObject new]本質(zhì)上并沒有什么區(qū)別怯邪,只是在分配內(nèi)存上面一個(gè)顯式的調(diào)用了alloc,一個(gè)隱式調(diào)用花墩。并且前者還可以調(diào)用自定義的一些其他init方法悬秉,而后者只能調(diào)用init方法。