博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
OC alloc、init、new
阅读量:7001 次
发布时间:2019-06-27

本文共 3668 字,大约阅读时间需要 12 分钟。

###[[NSObject alloc] init]两段式构造 #####1、对象分配,方法有alloc和allocWithZone:

流程图:

经过上面的一系列判断,过程最终是_class_createInstanceFromZone函数

static __attribute__((always_inline)) id_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,                               bool cxxConstruct = true,                               size_t *outAllocatedSize = nil){    if (!cls) return nil;    assert(cls->isRealized());    bool hasCxxCtor = cls->hasCxxCtor();// 判断当前class或者superclass 是否有.cxx_construct构造方法的实现    bool hasCxxDtor = cls->hasCxxDtor();// 判断判断当前class或者superclass 是否有.cxx_destruct析构方法的实现    bool fast = cls->canAllocNonpointer();// 是对 isa 的类型的区分,如果一个类和它父类的实例不能使用isa_t 类型的 isa 的话,fast 就为 false,但是在 Objective-C 2.0 中,大部分类都是支持的    // 获得分配的内存的大小    size_t size = cls->instanceSize(extraBytes);    if (outAllocatedSize) *outAllocatedSize = size;    id obj;    if (!zone  &&  fast) {        obj = (id)calloc(1, size); // 分配内存空间,calloc( )函数会默认的把申请出来的空间初始化为0或者nil        if (!obj) return nil;        obj->initInstanceIsa(cls, hasCxxDtor); // 初始化Isa指针    }     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); // 初始化Isa指针    }    if (cxxConstruct && hasCxxCtor) {        obj = _objc_constructOrFree(obj, cls);    }    return obj;}复制代码
inline void objc_object::initInstanceIsa(Class cls, bool hasCxxDtor){    initIsa(cls, true, hasCxxDtor);}inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) {     if (!nonpointer) {        isa.cls = cls;    } else {        isa_t newisa(0);        newisa.bits = ISA_MAGIC_VALUE;        newisa.has_cxx_dtor = hasCxxDtor;        newisa.shiftcls = (uintptr_t)cls >> 3;        isa = newisa;    }}复制代码

initIsa解析

1、newisa.bits = ISA_MAGIC_VALUE;从ISA_MAGIC_VALUE的定义中可以看到这个字段初始化了两个部分,一个是magic字段(6位:111011),一个是nonpointer字段(1位:1),magic字段用于校验,nonpointer之前已经详细分析过了。2、newisa.has_cxx_dtor = hasCxxDtor;这个字段存储类是否有c++析构器。3、newisa.shiftcls = (uintptr_t)cls >> 3;将cls右移3位存到shiftcls中,从isa_t的结构体中也可以看到低3位都是用来存储其他信息的,既然可以右移三位,那就代表类地址的低三位全部都是0,否则就出错了,补0的作用应该是为了字节对齐。uintptr_t nonpointer        : 1;  // 0 表示普通的 isa 指针,1 表示使用优化,存储引用计数uintptr_t has_assoc         : 1;  // 表示该对象是否包含 associated object,如果没有,则析构时会更快uintptr_t has_cxx_dtor      : 1;  // 表示该对象是否有 C++ 或 ARC 的析构函数,如果没有,则析构时更快uintptr_t shiftcls          : 33; // 类的指针uintptr_t magic             : 6;  // 固定值为 0xd2,用于在调试时分辨对象是否未完成初始化。uintptr_t weakly_referenced : 1;  // 表示该对象是否有过 weak 对象,如果没有,则析构时更快uintptr_t deallocating      : 1;  // 表示该对象是否正在析构uintptr_t has_sidetable_rc  : 1;  // 表示该对象的引用计数值是否过大无法存储在 isa 指针uintptr_t extra_rc          : 19; // 存储引用计数值减一后的结果复制代码

当我们通过 alloc 或 allocWithZone 方法创建对象时做以下 3 件事:

1、分配内存,会遍历该对象所有的成员变量,通过成员变量的类型来计算所需占用的内存 2、将该新对象的引用计数 (Retain Count) 设置成 1。 3、将该新对象的 isa 成员变量指向它的类对象。 4、将该新对象的所有其它成员变量的值设置成零。(根据成员变量类型,零有可能是指 nil 或 Nil 或 0.0)

#####2、对象初始化,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;}复制代码

_objc_rootInit 函数直接就将 obj 返回了,所以 -init 方法其实什么都没有做。

但是开发者留下的注释非常值得玩味,说到很多类没有使用 [super init],所以这个函数非常靠不住(很可能不被调用)。看起来应该是个历史遗留问题,从上面对 +alloc 的分析也能看出,+alloc 把所有的工作都做完了(初始化了 isa,我个人认为理论上初始化 isa 应该是 -init 的工作)。

#####3、new方法 new实际上是集alloc和init于一身,它创建了对象并初始化了对象。它的实现如下:

// 源码+ (id)new {    return [callAlloc(self, false/*checkNil*/) init];}// 可以这么理解+ (instancetype)new {  return [[self alloc] init];}复制代码

参考:

转载地址:http://vagvl.baihongyu.com/

你可能感兴趣的文章