iOS-OC

OC源码探索02:alloc、init和new的区别

2020-09-10  本文已影响0人  木扬音

准备工作

alloc源码探索

+ (id)alloc {
    return _objc_rootAlloc(self);
}
// 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*/);
}
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
    if (slowpath(checkNil && !cls)) return nil;//slowpath()真值判断
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {//判断一个类是否有自定义的+allocWithZone 实现,fastpath()假值判断
        return _objc_rootAllocWithZone(cls, nil);
    }
#endif

    // No shortcuts available. 没有可用的编辑器优化
    if (allocWithZone) {
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}

callAlloc方法中我们通过断点调试发现,是执行到_objc_rootAllocWithZone
其中 cls->ISA()->hasCustomAWZ()表示判断一个类是否有自定义的+allocWithZone 实现

NEVER_INLINE
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}
/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* Note: this function has been carefully written so that the fastpath
* takes no branch.
**********************************************************************/
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
                              int construct_flags = OBJECT_CONSTRUCT_NONE,
                              bool cxxConstruct = true,
                              size_t *outAllocatedSize = nil)
{
    ASSERT(cls->isRealized());//检查是否已经实现

    // Read class's info bits all at once for performance    一次性读取类的位信息以提高性能
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();
    size_t size;
    //计算需要开辟的内存大小,传入的extraBytes 为 0
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        //申请内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    if (!zone && fast) {
        //将 cls类 与 obj指针(即isa) 关联
        obj->initInstanceIsa(cls, hasCxxDtor);
    } else {
        // Use raw pointer isa on the assumption that they might be
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (fastpath(!hasCxxCtor)) {
        return obj;
    }

    construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
    return object_cxxConstructFromClass(obj, cls, construct_flags);
}

calloc源码

size_t instanceSize(size_t extraBytes) const {
    //编译器快速计算内存大小
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
        return cache.fastInstanceSize(extraBytes);
    }
    
    // 计算类中所有属性的大小 + 额外的字节数0
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    //如果size 小于 16,最小取16
    if (size < 16) size = 16;
    return size;
}
size_t fastInstanceSize(size_t extra) const
{
    ASSERT(hasFastInstanceSize(extra));

    //Gcc的内建函数 __builtin_constant_p 用于判断一个值是否为编译时常数,如果参数EXP 的值是常数,函数返回 1,否则返回 0
    if (__builtin_constant_p(extra) && extra == 0) {
        return _flags & FAST_CACHE_ALLOC_MASK16;
    } else {
        size_t size = _flags & FAST_CACHE_ALLOC_MASK;
        // remove the FAST_CACHE_ALLOC_DELTA16 that was added
        // by setFastInstanceSize
        //删除由setFastInstanceSize添加的FAST_CACHE_ALLOC_DELTA16 8个字节
        return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
    }
}
static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

内存对齐原则

字节对齐-总结

16字节对齐算法

字节对齐算法

calloc:申请内存,返回地址指针

obj = (id)calloc(1, size)通过instanceSize计算的内存大小,向内存中申请 大小 为 size的内存,并赋值给obj,因此 obj是指向内存地址的指针
这里我们可以通过断点调试的方式,来po obj观察obj的变化,未执行calloc前为nil,执行后为一个16进制地址

obj->initInstanceIsa:类与isa关联

这个过程主要是初始化一个isa指针,并将isa指针指向申请的内存地址,在将指针与cls类进行关联,同样也可以通过断点调试的方法,在执行完initInstanceIsa后,在通过po obj可以得出一个对象指针,而不是先前的16进制地址

alloc总结

alloc流程图

alloc流程图

init源码探索

init 类方法

这里的init是一个构造方法 ,是通过工厂设计,主要是用于给用户提供构造方法入口。这里能使用id强转的原因,主要还是因为内存字节对齐后,可以使用类型强转为你所需的类型

- (id)init {
    return _objc_rootInit(self);
}

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

new源码探索

通过源码可以得知,new函数中直接调用了callAlloc函数,且调用了init函数,所以可以得出new其实就等价于[alloc init]

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

猜你喜欢

热点阅读