美文网首页
OC底层 alloc & init & new 解析

OC底层 alloc & init & new 解析

作者: 旅行者_sz | 来源:发表于2020-09-08 15:07 被阅读0次

    前言:从对象的创建 , 去探究对象的本质 , 创建的流程 , 一路上会遇到 isa , 对象 -> ->元类 , cache_t, 内存对齐 , 分类 ,taggedPoint , 方法缓存, 方法查找, 消息转发, 内存管理等内容。对于iOS开发人员来说:alloc& init & new是非常熟悉的,但是是否对于它的原理也一的熟悉!,今天我们就一起探索一下这个我们熟悉的陌生人。流程图如下:

    底层流程图
    • 1.1 objc_alloc 与 alloc

    对象调用alloc

     CPPerson *objc1 = [LGPerson alloc];
    

    alloc类方法源码如下 :

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

    objc_alloc 函数如下 :

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

    我们可以看到不管是 alloc还是 objc_alloc , 都会进入callAlloc 这个函数 , 只是最后两个参数传入的不同 . 那么我们就继续往下看 .

    • 1.2callAlloc

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

    首先我们注意到了两个宏定义的函数 : fastpathslowpath .

    // x 很可能不为 0,希望编译器进行优化
    #define fastpath(x) (__builtin_expect(bool(x), 1))
    // x 很可能为 0,希望编译器进行优化
    #define slowpath(x) (__builtin_expect(bool(x), 0))
    
    • 1.2.1 _objc_rootAllocWithZone

    源码如下:

    _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.2.2. objc_msgSend

    源码如下:

        if (allocWithZone) {
            return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
        }
        return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
    
    • 1.3. _class_createInstanceFromZone

    源码如下:

    _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;
       
       //计算出需要的内存空间大小
       size = cls->instanceSize(extraBytes);
       if (outAllocatedSize) *outAllocatedSize = size;
    
       id obj;
       if (zone) {
           obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
       } else {
           // alloc 向系统申请开辟内存,返回地址指针
           obj = (id)calloc(1, size);
       }
       if (slowpath(!obj)) {
           if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
               return _objc_callBadAllocHandler(cls);
           }
           return nil;
       }
    
       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);
    }
    
    
    • 1.3.1 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;
       }
    
    • 1.3.2 calloc向内存申请空间,返回指针

    void    *calloc(size_t __count, size_t __size) __result_use_check __alloc_size(1,2);
    
    • 1.3.3 nitInstanceIsa(cls, hasCxxDtor);关联类

    objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
    {
       ASSERT(!cls->instancesRequireRawIsa());
       ASSERT(hasCxxDtor == cls->hasCxxDtor());
    
       initIsa(cls, true, hasCxxDtor);
    }
    
    • 2.1 init

    源码

    - (id)init {
      return _objc_rootInit(self);
    }
    
    _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;
    }
    
    

    可以看到init 默认返回方法调用者 . 这个设计其实是为了方便工程设计 , 以便于在初始化对象时做一些初始化或者赋值操作 .

    • 3.1 new

    源码

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

    new相当于 alloc +init . 但是使用new 并不能调用我们所重写的各种 init 工厂方法 .

    相关文章

      网友评论

          本文标题:OC底层 alloc & init & new 解析

          本文链接:https://www.haomeiwen.com/subject/tulkektx.html