美文网首页
alloc和new的区别

alloc和new的区别

作者: Crazy2015 | 来源:发表于2019-05-08 17:21 被阅读0次

在NSObject.mm文件中可以找到alloc方法和new方法的实现

***如果使用new的话,初始化方法就被固定调用init***
+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}

+ (id)alloc {
    return _objc_rootAlloc(self);
}

// Replaced by ObjectAlloc
+ (id)allocWithZone:(struct _NSZone *)zone {
    return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}

// 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*/);
}

alloc参数allocWithZone 为 true

1.alloc---->allocWithZone--->true
2.初始化的方式,不但可以通过init还可以通过initXXX

new参数allocWithZone 为 false
  1. new---->allocWithZone--->false
  2. 初始化的方式,固定调用init
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
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];
}
是否重写allocWithZone:方法
  • 没有重写allocWithZone:方法
    [cls new]分配内存的方式和[cls alloc]分配方式是一样的, 都是通过id obj = class_createInstance(cls, 0);来分配
  • 重写了allocWithZone:方法
    [cls new]创建对象的方式[cls alloc]方法,
    [cls alloc]创建对象的方式[cls allocWithZone:nil]方法

相关文章

网友评论

      本文标题:alloc和new的区别

      本文链接:https://www.haomeiwen.com/subject/idrvoqtx.html