美文网首页
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

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