OC底层 alloc & init & new 解析

2020-09-08  本文已影响0人  旅行者_sz

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

底层流程图

对象调用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 这个函数 , 只是最后两个参数传入的不同 . 那么我们就继续往下看 .

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

源码如下:

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

源码如下:

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

源码如下:

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

源码

   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;
   }
void    *calloc(size_t __count, size_t __size) __result_use_check __alloc_size(1,2);
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
   ASSERT(!cls->instancesRequireRawIsa());
   ASSERT(hasCxxDtor == cls->hasCxxDtor());

   initIsa(cls, true, hasCxxDtor);
}

源码

- (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 默认返回方法调用者 . 这个设计其实是为了方便工程设计 , 以便于在初始化对象时做一些初始化或者赋值操作 .

源码

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

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

上一篇下一篇

猜你喜欢

热点阅读