iOS底层学习笔记:对象alloc流程

99 阅读2分钟

最近开始了iOS底层的学习,为了更好的记忆知识点,故开始写一些文章来做笔记。

冲!

我们经常创建对象都会使用 [[xxx alloc] init] ,那么alloc方法做了什么,init又做了什么呢?

让我们来新建一个iOS项目,创建个自定义类,run一下:

    xxx *p1 = [xxx alloc];
    xxx *p2 = [p1 init];
    xxx *p3 = [p1 init];
    NSLog(@"%@ - %p - %p",object1,object1,&object1);
    NSLog(@"%@ - %p - %p",object2,object2,&object2);
    NSLog(@"%@ - %p - %p",object3,object3,&object3);

得到的结果是:

<xxx: 0x600003c9cc30> - 0x600003c9cc30 - 0x7ffee24cc0f8
<xxx: 0x600003c9cc30> - 0x600003c9cc30 - 0x7ffee24cc0f0
<xxx: 0x600003c9cc30> - 0x600003c9cc30 - 0x7ffee24cc0e8

&p1表示我是谁(我在栈上的位置),p1表示我指向的位置(指向堆的值的地址)。从打印的信息可以看出,alloc开辟了空间,而init只是持有了这个空间。

惊了还能这样的么?

所以这时候必须得看看源码了:Source Browser

首先我们得看alloc方法:

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

方法内部调用了_objc_rootAlloc()

id _objc_rootAlloc(Class cls) {
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

callAlloc()

static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
    if (slowpath(checkNil && !cls)) return nil;
    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));
}

这里通过断点发现调用了_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);
}

_class_createInstanceFromZone ()

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

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

可以看到_class_createInstanceFromZone()方法里面有核心的三个步骤:

  • size = cls->instanceSize(extraBytes)申请要开辟的内存大小
  • obj = (id)calloc(1, size)根据大小开辟的内存空间
  • obj->initInstanceIsa(cls, hasCxxDtor)将class和开辟的空间绑定

偷了个懒,图片来源:这里! alloc.webp

简单总结一下

整体来看,alloc的作用就是用来开辟空间并关联类,那么init呢? 我还没学完呢,学完再补!