alloc & init & new 源码分析

1. 初探

@interface YCPerson : NSObject
@end
@implementation YCPerson
@end

- (void)viewDidLoad {
    [super viewDidLoad];
    YCPerson *p1 = [YCPerson alloc];
    YCPerson *p2 = [p1 init];
    YCPerson *p3 = [p1 init];
    NSLog(@"%@ - %p - %p", p1, p1, &p1);
    NSLog(@"%@ - %p - %p", p2, p2, &p2);
    NSLog(@"%@ - %p - %p", p3, p3, &p3);
}

<YCPerson: 0x6000032e83c0> - 0x6000032e83c0 - 0x7ffee88e5618
<YCPerson: 0x6000032e83c0> - 0x6000032e83c0 - 0x7ffee88e5610
<YCPerson: 0x6000032e83c0> - 0x6000032e83c0 - 0x7ffee88e5608

从结果可以看出,3个对象是同一块内存空间 ,但 指向这个对象的3个指针是不一样的

指向这个对象的指针空间由栈分配,所以可以看到栈空间从高位到低位,依次降低。

又因为64位设备,指针大小为8字节,所以从 0x7ffee88e5618 每次减去 0x8。

2. 准备工作

3. alloc & init & new

3.1 alloc

  1. 通过断点进入 alloc

+ (id)alloc {
    return _objc_rootAlloc(self);
}
  1. 进入 _objc_rootAlloc
id _objc_rootAlloc(Class cls) {
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
  1. 进入 callAlloc
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false) {
#if __OBJC2__
    // checkNil 为false,!cls 也为false ,不会返回nil
    if (slowpath(checkNil && !cls)) return nil;
    // 是否有自定义的 +allocWithZone 实现
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        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));
}
  1. 通过断点调试,发现进入 _objc_rootAllocWithZone
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);
}
  1. 进入 _class_createInstanceFromZone ,新版的OBJC不再使用 zone 所以传了 nil
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)// alloc 源码 第五步
{
    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;

    // 1. 计算需要开辟的内存大小
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

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

    if (!zone && fast) {
        // 3. 设置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);
}

核心3步:

// 1. 计算需要开辟的内存大小
size = cls->instanceSize(extraBytes);
// 2. 申请内存
obj = (id)calloc(1, size);
// 3. 设置isa
obj->initInstanceIsa(cls, hasCxxDtor);

instanceSize 的实现,根据断点会执行以下几步:

size_t instanceSize(size_t extraBytes) const {
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
        return cache.fastInstanceSize(extraBytes);
    }
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    if (size < 16) size = 16;
    return size;
}

size_t fastInstanceSize(size_t extra) const {
    ASSERT(hasFastInstanceSize(extra));
    // __builtin_constant_p 用于判断一个值是否为编译时常数
    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
        // FAST_CACHE_ALLOC_DELTA16 8个字节
        return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
    }
}
// 16字节对齐算法
static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

总结一下:

  • alloc
  • _objc_rootAlloc
  • callAlloc
  • _objc_rootAllocWithZone
  • _class_createInstanceFromZone
    • instanceSize
    • calloc
    • initInstanceIsa

3.2 init

+ (id)init {
    return (id)self;
}

alloc 我们已经可以看出,此时的 self 即为一个开辟了一个实例对象大小, isa 指针指向其类对象的指针。

其实,在不存在其他成员变量的情况下,一个指向类对象的指针的指针,就是对象

指针的指针:obj->isa->cls

我的这篇文章 Runtime面试题与栈区参数2.1 部分详细分析了这个问题。

3.3 new

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

经过之前的分析,我们不难得出结论:new 等价于 [[ alloc] init]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。