美文网首页
iOS [[NSObject alloc] init]和[NSO

iOS [[NSObject alloc] init]和[NSO

作者: 天空知诚 | 来源:发表于2020-04-16 14:41 被阅读0次

直接查看源码

+ (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,只是前者传的第三个参数是true,后者没有传(即可能存在默认值)。

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];
}

根据callAlloc的实现,可以看到第三个参数默认是false,而纵观整个实现方法,只有最后两行代码用到了第三个参数。

if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];

可以看到allocWithZone为false的情况下,又回到了alloc方法。

总结

[[NSObject alloc] init]与[NSObject new]本质上并没有什么区别,只是在分配内存上面一个显式的调用了alloc,一个隐式调用。并且前者还可以调用自定义的一些其他init方法,而后者只能调用init方法。

相关文章

  • iOS [[NSObject alloc] init]和[NSO

    直接查看源码 从上面可知,两种方法都走的是callAlloc,只是前者传的第三个参数是true,后者没有传(即可能...

  • 【IOS】[[NSObject alloc]init]

    经常用 很少探究这个过程做的一些事情。整句代码就是创建了一个oc的实例对象。 整体 这里可以对应的三个值,代表的意...

  • OC的那些事

    NSObject * __weak someObject = [[NSObject alloc] init];, ...

  • 2019-03-05

    iOS : alloc 与 init 初探 继承nsobject的类在alloc时分配内存 此时即可直接使用 Pe...

  • [[NSObject alloc] init]

    示例代码: 思考1 一个 NSObject 对象会占用多少内存空间 思考2 alloc、init 分别进行了什么操...

  • 类对象和实例对象

    实例对象: NSObject *obj = [[NSObject alloc]init]; obj 就是实例对象,...

  • OC--alloc、init、new

    [[NSObject alloc] init]两段式构造 1、对象分配,方法有alloc和allocWithZon...

  • 强引用和弱引用

    __strong 和 __weak id obj1 = [[NSObject alloc] init]; 和 id...

  • 由 NSObject *obj = [[NSObject all

    来自掘金 《由 NSObject *obj = [[NSObject alloc] init] 引发的一二事儿》 ...

  • alloc 的初探

    开发中经常使用 NSObject *object = [[NSObject alloc] init]; 这行代码去...

网友评论

      本文标题:iOS [[NSObject alloc] init]和[NSO

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