iOS alloc流程分析

410 阅读6分钟

前言

  作为一名iOS开发人员,我们几乎天天和alloc、init绑在了一起,不管是我们写的代码抑或是看别人的代码,到处都充斥着alloc、init。那么你真的了解alloc么?你熟悉alloc的流程吗?alloc和init都承担着什么责任呢?下面的探索将为我们一点一点的解开alloc的面纱。

首先我们先看下面这段代码:

TStudent *s1 = [TStudent alloc];
TStudent *s2 = [s1 init];
TStudent *s3 = [s1 init];

NSLog(@"==s1==%@==%p==", s1, &s1);
NSLog(@"==s2==%@==%p==", s2, &s2);
NSLog(@"==s3==%@==%p==", s3, &s3);
==s1==<TStudent: 0x10063d300>==0x7ffeefbff408==
==s2==<TStudent: 0x10063d300>==0x7ffeefbff400==
==s3==<TStudent: 0x10063d300>==0x7ffeefbff3f8==

通过这段代码,我们可以看出s1、s2、s3的指针地址虽然不同,但是指向的对象却是同一个,也就是同一片内存空间。

TStudent *s1 = [TStudent alloc] 这行代码使用以下符号断点:alloc、objc_rootAlloc、callAlloc;运行代码会进入一段汇编程序,

此时我们读取寄存器里面的内容,就会发现,alloc具有申请内存空间、创建对象、并给指针赋予地址的能力。

(lldb) register read x0
      x0 = 0x0000000104da5600  (void *)0x0000000104da55d8: TStudent
(lldb) po 0x0000000104da5600
TStudent

alloc流程

下面我们就通过查看源码来看一下alloc在底层的实现流程:

当我们在调用alloc方法的时候,首先系统会调用一个[NSObject alloc]的方法:

// Calls [cls alloc].
id objc_alloc(Class cls)
{
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}

static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    if (slowpath(checkNil && !cls)) return nil;

#if __OBJC2__
    // 是否自定义allocWithZone
    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
        // 是否能快速alloc
        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);
            // 创建isa、关联对象
            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.
    // 当前类重写allocWithZone了,进入了[cls allocWithZone:nil]流程
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}

 由于我们还没做任何相关的alloc动作,所以在callAlloc(Class cls, bool checkNil, bool allocWithZone=false)这个方法里会直接走到[cls alloc],此时就会进入正常的alloc流程:

+ (id)alloc {
    return _objc_rootAlloc(self);
}

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

这时候就需要判断fastpath(!cls->ISA()->hasCustomAWZ()),判断当前类是否重写allocWithZone,由于我们当前类没有重写所以进入判断内部,接着判断fastpath(cls->canAllocFast()),此处判断默认为false,就会进入id obj = class_createInstance(cls, 0)方法里,在这个方法里系统就会申请内存空间,创建对象

id class_createInstance(Class cls, size_t extraBytes)
{ 
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}

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

    // Read class's info bits all at once for performance
    bool hasCxxCtor = cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();
    
    // 计算对象所需要的内存空间的大小
    size_t size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (!zone  &&  fast) {
        // 申请内存空间,创建对象
        obj = (id)calloc(1, size);
        if (!obj) return nil;
        // 初始化isa 关联类、对象
        obj->initInstanceIsa(cls, hasCxxDtor);
    } 
    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.
        // 初始化isa 关联类、对象
        obj->initIsa(cls);
    }

    if (cxxConstruct && hasCxxCtor) {
        obj = _objc_constructOrFree(obj, cls);
    }

    return obj;
}

size_t instanceSize(size_t extraBytes) {
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    if (size < 16) size = 16;
    return size;
}

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

    initIsa(cls, true, hasCxxDtor);
}

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);
        
        newisa.bits = ISA_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;

        // This write must be performed in a single store in some cases
        // (for example when realizing a class because other threads
        // may simultaneously try to use the class).
        // fixme use atomics here to guarantee single-store and to
        // guarantee memory order w.r.t. the class index table
        // ...but not too atomic because we don't want to hurt instantiation
        isa = newisa;
    }
}

那么此处就会有一个问题,我们需要申请多少内存空间呢?答案是能够放的下对象的这些属性。我们写的对象的属性如下:

@property (nonatomic, copy) NSString *name;     // 8
@property (nonatomic, assign) int age;          // 4
@property (nonatomic, assign) long height;      // 4
@property (nonatomic, strong) NSString *hobby;  // 8
@property (nonatomic, assign) char ch1;         // 1
@property (nonatomic, assign) char ch2;         // 1

由于对象的第一个属性isa,是一个隐藏属性,占用8字节的空间,加上这些属性,根据内存对齐原则,8+8+8(4+4)+8+8(1+1)= 40。
此处引入一个开辟内存空间的基本原则:字节对齐

define WORD_MASK 7UL
static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
static inline size_t word_align(size_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}

由以上代码总结下来就是:

  • 对象需要的内存空间是8的倍数,也就是8字节对齐
  • 最少是16字节

具体的内存对齐原则的相关描述可以查看 iOS内存对齐原则

申请内存,创建空间之后,那我们怎么把这块内存空间、对象、类关联起来呢?接着,我们顺着代码往下看,obj->initInstanceIsa(cls, hasCxxDtor)这一步就是初始化对象的isa,将内存空间、对象关联起来。

当我们所写的类重写了allocWithZone方法,就会进入_objc_rootAllocWithZone这个流程:

+ (id)allocWithZone:(struct _NSZone *)zone {
    return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}

id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
{
    id obj;
    // allocWithZone under __OBJC2__ ignores the zone parameter
    (void)zone;
    obj = class_createInstance(cls, 0);

    if (slowpath(!obj)) obj = callBadAllocHandler(cls);
    return obj;
}

  至此,alloc的流程我们基本上走了一遍,在这个过程中,alloc实现了开辟内存空间、创建对象、并且将内存空间和对象关联起来。总结可以得到以下流程图:

init

那么init又做了什么呢?我们先来看看底层代码的实现:

+ (id)init {
    return (id)self;
}

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

从代码可以看出,init返回的就是当前对象。这就是工厂设计模式的一种表现,方便子类重写、扩展。

new

new底层代码实现如下:

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

从代码可以看出,new其实就是[[XXX alloc] init],只是不同的写法。

fastpath

#define fastpath(x) (__builtin_expect(bool(x), 1))

这个指令的作用是将最有可能执行的分支告诉编译器,意思是:bool(x)为真的概率很大。

slowpath

#define slowpath(x) (__builtin_expect(bool(x), 0))

bool(x)为真的概率很小。