iOS 之1--alloc流程初探

2020-01-02  本文已影响0人  sz_蓝天使者

背景:在iOS中万物皆对像,平时我们在开发中经常用到alloc这个方法,但是底层是如何实现的呢!带着这个疑问我们一起从对象NSObject的初始化alloc开始探索。

一、前话:调试方法

在开始调试之前,我们先了解一下几种调试的方法
// 介绍三种方式// libobjc.A.dylib

  1. 下断点 : control + in - objc_alloc
  2. 下符号断点 objc_alloc: libobjc.A.dylib+[NSObject alloc]
  3. 汇编,通过Debug->Debug WorkFlow->Allway Show

Disassembly 打开汇编界面,可看到调用 libobjc.A.dylib`objc_alloc:

二、alloc流程分析

#import <Foundation/Foundation.h>
#import "MyTeacher.h"
#import <objc/runtime.h>
#import <malloc/malloc.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // size :
        // 1: 对象需要的内存空间 8倍数 - 8字节对齐
        // 2: 最少16 安全 16 - 8  > 16
        MyTeacher  *p = [MyTeacher alloc];//此处打断点
        NSLog(@"%@",p);
    }
    return 0;
}
+ (id)alloc {
    return _objc_rootAlloc(self);
}
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
 /* 省略代码*/
        // canAllocFast返回值固定为false,内部调用了一个bits. canAllocFast, 所以创建对象暂时看来只能用到else中的代码
        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);
            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;
        }
   /* 省略代码*/
}
id 
class_createInstance(Class cls, size_t extraBytes)
{
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}
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) {//********此时为true,会执行以下代码******
        obj = (id)calloc(1, size);
        if (!obj) return nil;
        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.
        obj->initIsa(cls);
    }

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

    return obj;
}

详细解读
①hasCxxCtor()
hasCxxCtor()是判断当前class或者superclass是否有.cxx_construct 构造方法的实现
②hasCxxDtor()
hasCxxDtor()是判断判断当前class或者superclass是否有.cxx_destruct 析构方法的实现
③canAllocNonpointer()
anAllocNonpointer()是具体标记某个类是否支持优化的isa
④instanceSize()
instanceSize()获取类的大小(传入额外字节的大小)
已知zone=false,fast=true,则(!zone && fast)=true
⑤calloc()
用来动态开辟内存,没有具体实现代码,接下来的文章会讲到malloc源码
⑥initInstanceIsa()
内部调用initIsa(cls, true, hasCxxDtor)初始化isa

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

uint32_t alignedInstanceSize() {
  return word_align(unalignedInstanceSize());
}

// May be unaligned depending on class's ivars.
//读取当前的类的属性数据大小
uint32_t unalignedInstanceSize() {
  assert(isRealized());
  return data()->ro->instanceSize;
}
//进行内存对齐
//WORD_MASK == 7
static inline uint32_t word_align(uint32_t x) {
   return (x + WORD_MASK) & ~WORD_MASK;
}

以下是内存对齐的算法(参考了我是好宝宝 写的内容),此内容通俗易懂。

假如: x = 9,已知WORD_MASK = 7

x + WORD_MASK = 9 + 7 = 16
WORD_MASK 二进制 :0000 0111 = 7 (4+2+1)
~WORD_MASK : 1111 1000
16二进制为  : 0001 0000
 
1111 1000
0001 0000
---------------
0001 0000 = 16

所以 x = 16    也就是 8的倍数对齐,即 8 字节对齐

作者:我是好宝宝
链接:https://juejin.im/post/5df6323d6fb9a016317813b0
来源:掘金
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.
 obj->initIsa(cls);

三、init & new

- (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;
}
+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}

总结:

    1. alloc 申请的内在空间是以8为倍数,且最小为16bit;
    1. init 没做什么事,就为了方便开发者扩展;
    1. new 就是alloc 和 init 的集合。

最后看一张alloc的流程图,此图根据objc的源码经以上分析得来。

alloc 流程.png

参考:
苹果的开源代码
Coci老师的调试objc源码的方法
iOS探索 alloc流程 (by我是好宝宝)

上一篇 下一篇

猜你喜欢

热点阅读