【iOS】alloc、init、new - 详解

1. alloc

进入到alloc的源码里面,我们发现alloc调用了_objc_rootAlloc方法,而_objc_rootAlloc调用了callAlloc方法。

+ (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 (slowpath(checkNil && !cls)) return nil;
#if __OBJC2__
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
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];
}

具体内容本人暂时也一知半解,贴一张图
请添加图片描述

alloc为我们创建了1个对象并申请了一块不小于16字节的内存空间

具体可以参考一下这篇博客
博客

2. init

我们进入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;
}

额的天呐,init啥都没做,只是把当前的对象返回了。既然啥都没做那我们还需要调用init吗?答案是肯定的,其实init就是一个工厂范式,方便开发者自行重写定义。

我们在来看看new方法做了啥。

3. init

我们再看看init的代码

+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}

init调用的是callAlloc的方法和init,那么可以理解为new实际上是alloc + init的综合体。

4. 总结

  1. alloc创建了对象并且申请了一块不少于16字节的内存空间。
  2. init其实什么也没做,返回了当前的对象。其作用在于提供一个范式,方便开发者自定义。
  3. new其实是alloc+init的一个综合体。
posted @ 2025-10-24 19:39  wzzkaifa  阅读(2)  评论(0)    收藏  举报