美文网首页
alloc&init&new探索

alloc&init&new探索

作者: 丸疯 | 来源:发表于2020-09-07 17:37 被阅读0次

在iOS开发中我们创建对象一般都是[[Class alloc] init],或者[Class new],这两者有什么区别。alloc做了什么?init又干了什么?new和他们之间又有什么联系?
我们通过下面这段代码和输出来展开主题:

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

执行之后我们得到

<Person: 0x600002d13210> - 0x600002d13210 - 0x7ffeebc2e138
<Person: 0x600002d13210> - 0x600002d13210 - 0x7ffeebc2e130
<Person: 0x600002d13210> - 0x600002d13210 - 0x7ffeebc2e128

%@,对对象进行打印,得到对象和对象所在的内存地址
%p,对对象地址进行打印,得到对象在内存中的地址(指针指向的地址)
&p,取地址符,结合%p可以得到指针所在的内存地址(指针地址)
p1,p2,p3,都指向同一块内存地址,不同的是p1,p2,p3自身的内存地址不一样,我们还可以看出p1,p2,p3在内存中是连续

指向这个对象的指针空间由栈分配,所以可以看到栈空间从高位到低位,依次降低。
又因为64位设备,指针大小为8字节,所以从 0x7ffeebc2e138 每次减去 0x8。

我们通过断点发现alloc进去了之后,并没有alloc的实现方式。还好Apple对这部分的实现进行了开源。

准备工作

获取Apple最新的开源代码开源代码公布地址
编译源码:参考Cooci Github

alloc探索

1 通过对alloc进行断点,我们看到首先执行了 _objc_rootAlloc

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

2 继续跟进,开始执行callAlloc

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

3 继续跟进,来到了callAlloc的内部实现

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

4 断点大法告诉我们接下来执行_objc_rootAllocWithZone

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

新版的OBJC不再使用 zone 所以传了 nil

5 接下来就是_class_createInstanceFromZone

_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) {
        // 设置Isa
        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);
}

这么多,怎么看啊?
其实最主要的就是三部分:

    // 计算需要的内存大小
    size = cls->instanceSize(extraBytes);
    // 开辟内存空间
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        obj = (id)calloc(1, size);
    }
    // 设置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);
    }
  • 在instanceSize主要执行了下面几部
size_t instanceSize(size_t extraBytes) const {
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
        return cache.fastInstanceSize(extraBytes);
    }
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    if (size < 16) size = 16;
    return size;
}

size_t fastInstanceSize(size_t extra) const {
    ASSERT(hasFastInstanceSize(extra));
    // __builtin_constant_p 用于判断一个值是否为编译时常数
    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
        // FAST_CACHE_ALLOC_DELTA16 8个字节
        return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
    }
}
// 16字节对齐算法
static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

所以alloce的流程


alloc流程图.png

init

我们对init进行断点发现

- (id)init {
    return _objc_rootInit(self);
}

直接返回了传入的本身,Apple为我们提供了可供重写的构造方法。

new

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

在没有重写init方法的时候,[Class new]其实和 [[Class alloc] init]是一样的.

相关文章

网友评论

      本文标题:alloc&init&new探索

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