美文网首页
源码分析之 alloc & init & new

源码分析之 alloc & init & new

作者: HLinzl | 来源:发表于2020-09-07 16:37 被阅读0次

初识底层

HLPerson *p1 = [HLPerson alloc];
HLPerson *p2 = [p1 init];
HLPerson *p3 = [p1 init];
HLNSLog(@"%@ - %p - %p",p1,p1,&p1);
HLNSLog(@"%@ - %p - %p",p2,p2,&p2);
HLNSLog(@"%@ - %p - %p",p3,p3,&p3);  

打印结果:
<HLPerson: 0x600003d14130> - 0x600003d14130 - 0x7ffeed69d0f8
<HLPerson: 0x600003d14130> - 0x600003d14130 - 0x7ffeed69d0f0
<HLPerson: 0x600003d14130> - 0x600003d14130 - 0x7ffeed69d0e8

根据打印结果可以看出:

p1、p2、p3这三个对象指向的是同一片内存空间;
指向这三个对象的指针是不同的,由于指针空间是由栈来分配,因此这三个指针的地址是连续的,从高位到低位依次降低8个字节(由于是64位设备)。

无源码底层原理探索

方法1、直接添加符号表

  • 左侧导航栏切换到断点模块;
  • 点击左下角‘➕’,选择添加‘symbol breakPoint’;
  • 在symbol一栏输入需要debug的方法名字。

方法2、汇编查看跟踪流程

  • 在 Debug -> Debug Workflow下切换至Always Show Disassembly模式
  • 通过符号断点查看源码出处

alloc & init & new 探索

!!!编译和debug苹果官方源码的方法,可以参考这篇文章

1、alloc

  • 通过断点,可以进入alloc的具体实现

    + (id)alloc {
      return _objc_rootAlloc(self);
    }
    
  • command+鼠标左键,进入_objc_rootAlloc方法

 id _objc_rootAlloc(Class cls) {
   return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
 }
  • command+鼠标左键,进入callAlloc方法
 static ALWAYS_INLINE id
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));
}
  • callAlloc中,可以发现有多个实现分支,断点可以发现,进入的是_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);
}
  • command+鼠标左键,进入_class_createInstanceFromZone方法
  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;

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

在最后执行的_class_createInstanceFromZone方法中,调用了许多方法,其中有三个方法最为重要。

// 计算需要分配的内存大小
size = cls->instanceSize(extraBytes);
// 申请内存空间
obj = (id)calloc(1, size);
// 绑定isa与obj
obj->initInstanceIsa(cls, hasCxxDtor);

断点进入instanceSize方法,可以跟踪后续流程。

cache.fastInstanceSize(extraBytes)
//字节对齐
align16(size + extra - FAST_CACHE_ALLOC_DELTA16)

最后附上流程图。

image.png

2、init & new

2.1 new的实现
通过command + 鼠标左键进入new的具体的实现,可以看到,其本质就是调用了一次alloc和init。

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

但是不推荐使用new,因为在很多场景下,大部分开发者都会有自己的构造方法,如-initWithXXX:(id)xx,而new方法只能实现-init,调用不到自定义的构造方法。

2.2 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方法其实返回的还是当前对象,这就解释了开篇,为什么p1、p2、p3指向的内存空间是一样的。

相关文章

网友评论

      本文标题:源码分析之 alloc & init & new

      本文链接:https://www.haomeiwen.com/subject/ljflektx.html