iOS对象alloc探究

812 阅读3分钟

前言

对象alloc、init写了很多年,但是对于alloc里面的内部实现只知道创建了一个对象,分配了一个存储对象的内存空间。但是它是如何分配空间,分配的内存大小是多少?,分配的内存是怎么跟类关联的等等都一知半解,今天带着这些疑问,探究一下alloc内部实现.

前期准备

apple开源网站下载objc4源代码,里面有很多版本,由于最新的版本objc4——824现在无法下载,所以我选择的是objc4-818.2版本进行下载。下载完成之后的代码是不可以直接编译的,需要自己去配置,配置过程可以看这篇博客:iOS-底层原理 03:objc4-781 源码编译 & 调试

开始探究

1.alloc与init的作用

    ZFPerson *p = [ZFPerson alloc];
    ZFPerson *p1 = [p init];
    ZFPerson *p2 = [p init];
    
    NSLog(@"p = %@ pAddr = %p",p,&p);
    NSLog(@"p1 = %@ p1Addr = %p",p1,&p1);
    NSLog(@"p2 = %@ p2Addr = %p",p2,&p2);

打印的结果

p = <ZFPerson: 0x10123b230> pAddr = 0x7ffeefbff3f8
p1 = <ZFPerson: 0x10123b230> ·p1Addr = 0x7ffeefbff3e8
p2 = <ZFPerson: 0x10123b230> p2Addr = 0x7ffeefbff3f0

从打印的结果我们可以得出p1,p2,p3指针,指向的内存空间是同一块,为了方便理解我画了下面这么一张图

image.png

结论: 1.alloc具有分配内存空间的作用 2.init只是类的构造方法,不具备开辟内存空间的能力

2.alloc的探究

image.png 创建一个ZFPerson对象,command+点击alloc,跟进alloc内部,发现alloc内部会调用callAlloc函数,在callAlloc打上一断点发现会有很多地方都在调用callAlloc函数

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

image.png

那么问题就来了,我们调用alloc->callAlloc函数执行流程是不是alloc->_objc_rootAlloc——>callAlloc流程呢?抱着这个疑问,看了一下堆栈信息

image.png 很明显调用alloc的时候,底层没有调用alloc函数,而是调用了objc_alloc函数。 (猜测底层做了hook处理,暂不探究)继续执行断点会发现函数会执行到objc_msgSend(cls, @selector(alloc),也就是会走到alloc函数中

image.png 到这里先画一个流程图总结一下alloc流程

image.png 现在流程走到了_objc_rootAllocWithZone函数

image.png,继续走到了_class_createInstanceFromZone函数。

3.alloc流程核心方法探究

进到_class_createInstanceFromZone函数发现内部在计算内存大小,分配空间,关联类的isa指针,所以这就是alloc内部实现核心代码。
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(); //加载类缓存里面的bit信息
    bool fast = cls->canAllocNonpointer();
    size_t size;
    //1.计算开辟空间大小
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    //2.开辟内存
    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }
    //3.绑定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);
}

3.1 计算内存大小cls->instanceSize

   inline size_t instanceSize(size_t extraBytes) const {
       //获取缓存内存大小,并且16字节对齐
       if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
           return cache.fastInstanceSize(extraBytes);
       }
       //计算内存大小以及内存对齐 extraBytes = 0
       size_t size = alignedInstanceSize() + extraBytes;
       // CF requires all objects be at least 16 bytes.
       if (size < 16) size = 16;
       return size;
   }

进入instanceSize函数发现,获取instanceSize的方式有两种,一种是从缓存中获取,另外一种从类的数据中获取

3.1.1 fastInstanceSize

size_t fastInstanceSize(size_t extra) const {
    ASSERT(hasFastInstanceSize(extra));

    if (__builtin_constant_p(extra) && extra == 0) {
        return _flags & FAST_CACHE_ALLOC_MASK16;
    } else {
        size_t size = _flags & FAST_CACHE_ALLOC_MASK;
        // remove the FAST_CACHE_ALLOC_DELTA16 that was added
        // by setFastInstanceSize
        //16字节对齐
        return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
    }
}
static inline size_t align16(size_t x) {
//16字节对齐
return (x + size_t(15)) & ~size_t(15);
}

3.1.2 alignedInstanceSize 方式

// Class's ivar size rounded up to a pointer-size boundary.
uint32_t alignedInstanceSize() const {
     //内存对齐,unalignedInstanceSize()获取为对齐的内存大小
    return word_align(unalignedInstanceSize());
}
// May be unaligned depending on class's ivars.
uint32_t unalignedInstanceSize() const {
    ASSERT(isRealized());
    //获取实例大小
    return data()->ro()->instanceSize;
}

3.2 开辟内存calloc(1, size)

image.png

3.3 绑定isa

image.png 具体流程是创建一个isa指针与类关联,最后与obj关联

objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    initIsa(cls, true, hasCxxDtor);
}
inline void 
objc_object::initIsa(Class cls, bool nonpointer, UNUSED_WITHOUT_INDEXED_ISA_AND_DTOR_BIT bool hasCxxDtor)
{ 
    
    isa_t newisa(0); //初始化一个isa指针
    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.setClass(cls, this); //关联类上
    newisa.extra_rc = 1;

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

4.总结

4.1 对象alloc的流程就是

objc_alloc->callAlloc->alloc->_objc_rootAlloc->callAlloc->_objc_rootAllocWithZone->_class_createInstanceFromZone->(cls->instanceSize(extraBytes))->calloc(1, size)->(obj->initInstanceIsa)

4.2 alloc一个对象的核心步骤

  1. 获取类的内存大小size
  2. 分配大小为size的内存空间
  3. 将分配的空间与类的isa进行关联