iOS 中对象的创建过程

iOS 开发中所有的类都是继承自 NSObject 来的(除了个别的, 比如 NSProxy). 也几乎没有类会去重写 alloc 方法, 接下来, 就以 NSObject 为例分析一下
创建一个对象的过程都要 alloc, 例如 [NSObject alloc];
alloc 中发生了什么呢?
ps: 下载源代码的同学, 打开之前先把 old 文件删掉, 要不然一会儿又到old 文件里面去了, 心累

// https://opensource.apple.com/source/objc4/objc4-709/runtime/NSObject.mm.auto.html
+(id)alloc {
    return _objc_rootAlloc(self);
}

这里直接跳转到 _objc_rootAlloc

// 同上文件, 这里略微整理了一下
id _objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

继续

// 同上文件
static 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];
}

slowpath 和 fastpath 是一个编译器优化的东西, 我们这里分析源代码就直接忽略了.
#if __OBJC2__ 这个判断一定为真, 现在用的都是 objc2.0 了
精简一下代码

static id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    if (checkNil && !cls) return nil;
    
    if (!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;
        }
    }
    
    // No shortcuts available.
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}

然后根据之前传过来的参数, checkNil 是 false, 第一个 if 就没用了, 第二个 if , 如果有自定义的 allocWithZone 就不使用这下面默认的了, 这里是没有自定义的.
canAllocFast, 目前所有的类都是返回 false. 所以再精简一下

static id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    
    // 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;
}

这就很简单了
第一句创建对象, 第二句错误处理, 然后就返回了

//https://opensource.apple.com/source/objc4/objc4-709/runtime/objc-runtime-new.mm.auto.html
id class_createInstance(Class cls, size_t extraBytes)
{
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}

继续

static id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, 
                              bool cxxConstruct = true, 
                              size_t *outAllocatedSize = nil)
{
    if (!cls) return nil;// 首先是判断是否为空

    assert(cls->isRealized());// 检查是否已经realize 了

    // Read class's info bits all at once for performance
    bool hasCxxCtor = cls->hasCxxCtor();// 对 C++ 混编的支持, 这里略过
    bool hasCxxDtor = cls->hasCxxDtor();// 对 C++ 混编的支持, 这里略过
    bool fast = cls->canAllocNonpointer();// objc 2.0 都是返回 true 

    size_t size = cls->instanceSize(extraBytes); // 这一步是获取对象大小的, 这样才能分配合适的空间保存对象. 稍后再讲
    if (outAllocatedSize) *outAllocatedSize = size;
//这下面开始创建对象了
    id obj;
    if (!zone  &&  fast) {
    // 基本都是走这一个分支
        obj = (id)calloc(1, size); // 分配空间, calloc 会把分配好的内存空间全部值为0, 这就是为什么没有初始化的属性都是0, nil, false 的原因
        if (!obj) return nil;
        obj->initInstanceIsa(cls, hasCxxDtor);// 初始化
    } 
    else {
        //这个分支下面可以跳过不用看了
        if (zone) {
            obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
        } else {
            obj = (id)calloc(1, size);
        }
        if (!obj) return nil;

        // Use raw pointer isa on the assumption that they might be 
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }
    // 混编的处理部分, 这里略过
    if (cxxConstruct && hasCxxCtor) {
        obj = _objc_constructOrFree(obj, cls);
    }

    return obj;
}

其中检查 isRealized 的部分可以看这篇文章
fast 部分引用一下别人的

而 fast,是对 isa 的类型的区分,如果一个类的实例不能使用 isa_t 类型的 isa 的话,fast 就为 false,但是在 Objective-C 2.0 中,大部分类都是支持的。关于 isa 的类型,可以看看「Objective-C 小记(1)Messaging」和「Objective-C 小记(2)对象 2.0」。

获取对象尺寸的部分, 借用一些别人写的

不难看出就是从 cls 的 ro 中获得 instanceSize 然后将它对齐,并加上 extraBytes,最后 Core Foundation 需要对象至少要有 16 字节,小于 16 的统统返回 16。

    //https://opensource.apple.com/source/objc4/objc4-709/runtime/objc-runtime-new.mm.auto.html
    // May be unaligned depending on class's ivars.
    uint32_t unalignedInstanceSize() {
        assert(isRealized());
        return data()->ro->instanceSize;
    }

    // Class's ivar size rounded up to a pointer-size boundary.
    uint32_t alignedInstanceSize() {
        return word_align(unalignedInstanceSize());
    }

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

初始化部分, 去掉 assert 之后, 其实就是使用initIsa 进行初始化.

//https://opensource.apple.com/source/objc4/objc4-709/runtime/objc-object.h.auto.html
inline void 
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    assert(!cls->instancesRequireRawIsa());
    assert(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}
inline void 
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    assert(!isTaggedPointer()); 
    
    if (!nonpointer) {// nonpointer 这个参数是 true
        isa.cls = cls;
    } else {
        assert(!DisableNonpointerIsa);
        assert(!cls->instancesRequireRawIsa());

        isa_t newisa(0);// 创建一个 newisa

#if SUPPORT_INDEXED_ISA
// 这个宏, 是判断由这个宏判断的, __ARM_ARCH_7K__
// 网上找了一下资料, 应该是 apple watch 会走这个代码
// 直接去看 else 部分
        assert(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        // 这里是对 newisa 初始化
        newisa.bits = ISA_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;//将位移(shift)后的 cls 存入 shiftcls(类指针按照 8 字节对齐,所以最后三位一定是 0,所以可以右移三位来节省位的使用)
#endif

        // This write must be performed in a single store in some cases
        // (for example when realizing a class because other threads
        // may simultaneously try to use the class).
        // fixme use atomics here to guarantee single-store and to
        // guarantee memory order w.r.t. the class index table
        // ...but not too atomic because we don't want to hurt instantiation
        // 最后就是保存一下 isa, 完成了
        isa = newisa;
    }
}

最后总结一下, 这么多的代码, 其实大部分都是跳来跳去的,
这里去掉一些判断, 断言, 跳转这些, 直接看一下实际调用的代码

+ (id)alloc {
    return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls) {
    size_t size = word_align(cls->data()->ro->instanceSize);// 获取对象大小
    id obj = (id)calloc(1, size); // 分配内存
    isa_t newisa(0);
    newisa.bits = ISA_MAGIC_VALUE;
    newisa.shiftcls = (uintptr_t)cls >> 3;
    obj->isa = newisa;// 保存 isa
    return obj;
}

实际上就三步, 获取大小, 分配内存, 保存 isa 就完了.其实也是很简单的对吧!
部分源自于 KylinRoc 的文章Objective-C 小记(6)alloc & init

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容