iOS——runtime(4):浅析对象的建立

分析

在咱们的main.m中输入如下代码:程序员

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    NSObject *obj = [[NSObject alloc] init];
    return 0;
}
复制代码

这段代码相信你们一眼就能看懂。那么,在代码objective-c

NSObject *obj = [[NSObject alloc] init];
复制代码

执行的过程当中究竟发生了什么,你们是否了解呢。本文就带你们研究一下alloc函数的实现过程。bash

alloc函数

进入 alloc函数,咱们不难发如今文件NSObject.m中已经有其实现:函数

+ (id)alloc {
    return _objc_rootAlloc(self);
}
复制代码

咱们继续查看_objc_rootAlloc函数:测试

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

继续查看函数callAllocui

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]; } 复制代码

这段比较长,咱们稍微分析一下:this

#if __OBJC2__
用于判断objective-c 版本,是否是2.0,目前咱们使用的objective-c版本都是此版本。spa

slowpathfastpath
其内部实现以下code

#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
复制代码

所以其实就是了解__builtin_expect这个指令:对象

__builtin_expect这个指令是gcc引入的,做用是容许程序员将最有可能执行的分支告诉编译器。这个指令的写法为:__builtin_expect(EXP, N)。
意思是:EXP==N的几率很大。

因此fastpath的含义是,为1的几率大,slowpath的含义是为0的几率大。

知道了这几点,相信以上代码应该能大体读懂,将以上代码进行注释和省略部分宏定义以下:

static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    if (slowpath(checkNil && !cls)) return nil;
//若是该对象没有本身的allocWithZone方法须要实现
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
    //查看一下类是否能快速分配内存
        if (fastpath(cls->canAllocFast())) {
        //查看一下类是否有析构函数
            bool dtor = cls->hasCxxDtor();
            //分配内存,给obj对象
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());
            //若是分配失败,那么交给错误处理
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            //初始化obj的isa
            obj->initInstanceIsa(cls, dtor);
            return obj;
        }
        else {
            id obj = class_createInstance(cls, 0);
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            return obj;
        }
    }

    //若是allocWithZone 为true,则实现allocWithZone 方法
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}
复制代码

看过笔者前面文章的读者应该能大体理解上面代码的含义了。主要运行了以下逻辑:

  1. 建立对象并分配内存
  2. 初始化isa属性

建立对象这个很少说了,无非是获取对象大小,而后分配内存。初始化isa这一步其实还有一些逻辑,进入方法initInstanceIsa能够看到:

inline void 
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    assert(!cls->instancesRequireRawIsa());
    assert(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}
复制代码

继续进入方法:initIsa

inline void 
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    assert(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa.cls = cls;
    } else {
        assert(!DisableNonpointerIsa);
        assert(!cls->instancesRequireRawIsa());
        isa_t newisa(0);
#if SUPPORT_INDEXED_ISA
        assert(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        newisa.bits = ISA_MAGIC_VALUE;
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
        isa = newisa;
    }
}
复制代码

这里对以上代码作个初步分析:

TaggedPointer
暂不作介绍,你们能够先不用理解,后面的文章会给出分析。

SUPPORT_INDEXED_ISA
表示 isa_t 中存放的 Class 信息是 Class 的地址,仍是一个索引(根据该索引可在类信息表中查找该类结构地址)。经测试,iOS 设备上 SUPPORT_INDEXED_ISA 是 0。

所以以上代码能够简写成:

inline void 
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    assert(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa.cls = cls;
    } else {
        assert(!DisableNonpointerIsa);
        assert(!cls->instancesRequireRawIsa());
        //建立isa对象
        isa_t newisa(0);
        //设置占位bits
        newisa.bits = ISA_MAGIC_VALUE;
        //有无析构函数
        newisa.has_cxx_dtor = hasCxxDtor;
        //咱们熟悉的存储对象类信息的字段
        newisa.shiftcls = (uintptr_t)cls >> 3;
        //赋值
        isa = newisa;
    }
}
复制代码

init函数

init函数的实现相对来讲很是简单了,咱们看一下他的调用栈:

- (id)init {
    return _objc_rootInit(self);
}
复制代码

继续分析_objc_rootInit

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;
}
复制代码

总结

本文经过分析代码:

NSObject *obj = [[NSObject alloc] init];
复制代码

带领你们分析了一下对象的建立过程,但愿对你们理解对象建立有必定帮助。



做者:kyson

地址:www.jianshu.com/p/b928473c7…

相关文章
相关标签/搜索