IOS开发知识点

iOS底层探究-alloc/init做了什么?

2020-09-08  本文已影响0人  羅__

前言

想必大家做开发的时候敲过无数遍 [[XXX alloc] init],那么alloc函数到底做了什么工作知道吗,不就是对象初始化开辟内存嘛,那你能详细点描述具体流程吗?这时候就一脸懵逼,what?今天笔者就带大家来探索下alloc函数具体做了什么。
大家先来看下面代码打印的日志,分别打印了p1p2p3三个指针指向的内容,指向的内存地址,指针地址。

图1
我们发现这三个指针指向的内容和内存地址是一样的,由p1p2可以看出alloc后对象就已经创建一个对象并且分配好内存了,接下来init函数似乎只是初始化一个指针来指向alloc创建的对象。那么我们接下来就通过源码去探索alloc/init做了什么。

准备

开始追踪objc源码查看alloc具体操作

// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__  //objc有两个版本 ,OBJC2为编译优化版本
    if (slowpath(checkNil && !cls)) return nil;
    //判断这个类是否有自定义的 +allocWithZone 实现,没有则走到if里面的实现
    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));
}

我们编译断点调试发现走到了if __OBJC2__里面,调用的_objc_rootAllocWithZone

id
_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);
}
static ALWAYS_INLINE id
_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;
    // 1:要开辟多少内存
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        // 2;怎么去申请内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    // 3: 将 cls类 与 obj指针(即isa) 关联
    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);
}

我们发现alloc做了三件事

  1. cls->instanceSize(extraBytes); 计算需要开辟的内存空间大小。
  2. calloc 根据size申请内存,然后返回该内存地址的指针。
  3. obj->initInstanceIsa 将 cls类 与 obj指针(即isa) 关联。

接下来我们看看init做了什么

- (id)init {
  if (self = [super init]) {
    self.name = @"张三";
  }
  return self;
}

所以整个alloc/init大致流程如下


alloc/init流程

总结

一句话概括就是alloc做了三件事1. cls->instanceSize(extraBytes);计算对象需要多大内存空间。2.调用calloc函数申请内存并返回内存的指针地址。3.obj->initInstanceIsa 将 cls类 与 obj指针(即isa) 关联。 init做了一件事就是返回当前对象。

对于第二步 calloc 根据size申请内存,然后返回该内存地址的指针。和第三步 obj->initInstanceIsa 将 cls类 与 obj指针(即isa) 关联,比较简单明了就不多说了,下一遍博客主要讲下第一步cls->instanceSize(extraBytes); 计算需要开辟的内存空间大小。里面涉及到内存字节对齐和为什么苹果要这样做。

上一篇 下一篇

猜你喜欢

热点阅读