alloc做了什么

背景:小一同学从小是一个粗心的孩子。有时候,小一突然会发现自己穿了两只不一样的袜子,晚上睡觉的时候,小一突然发现里面的长袖穿反了。后来小一成为了一名程序员。
复制代码

what happened?

小一在熟练的创建”对象“,Person *p = [Person alloc] ..., ”啊,这个什么情况?“,小一被巨大的吵闹吸引了过去,凑完热闹,小一又回来给继续给对象赋值,”哦豁,我忘记写init了,(⊙o⊙)…,但是好像还可以用,发生了什么呢?“,于是小一就开始了如下的探索。
复制代码
    Person *p = [Person alloc];
    Person *p1 = [p init];
    Person *p2 = [p init];
    Person *p3 = [p init];
    
    NSLog(@"%@---%p",  p, &p);
    NSLog(@"%@---%p",  p1, &p1);
    NSLog(@"%@---%p",  p2, &p2);
    NSLog(@"%@---%p",  p3, &p3);
2021-06-12 11:58:14.656070+0800 alloc1[33225:10170125] <Person: 0x600003f2c190>---0x7ffee6bb8108
2021-06-12 11:58:14.656257+0800 alloc1[33225:10170125] <Person: 0x600003f2c190>---0x7ffee6bb8100
2021-06-12 11:58:14.656411+0800 alloc1[33225:10170125] <Person: 0x600003f2c190>---0x7ffee6bb80f8
2021-06-12 11:58:14.656596+0800 alloc1[33225:10170125] <Person: 0x600003f2c190>---0x7ffee6bb80f0
复制代码

分析上面的结果:p、p1、p2、p3他们指向的地址是相同的,但是他们本身的地址是不同的,相差8。也就是说:对象的分配是在alloc中完成的,然后p1、p2、p3是指向对象的指针,他们的内存分配在栈中,地址分配由高到低,所以才有了上面的打印,下面我们就来看一下alloc里面发生了什么?init是干嘛的?

why

alloc流程

流程图如下:

截屏2021-06-12 下午3.04.04.png

关键源码分析(以objc 818为例,xcode12.5)
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. 兼容老的zone方法
    if (allocWithZone) {
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
复制代码

经过调用栈调用最后调动_class_createInstanceFromZone这个方法
这个方法阐述了对象是如何分配内存的

  1. 要先计算内存大小
  2. 分配内存空间
  3. 与传入的对象关联
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;
    //1.计算内存大小
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
    //2.分配内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    if (!zone && fast) {
    //3.关联当前cls
        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);
}
复制代码

1.从内存的大小计算中可以看出,818是以16字节对齐的。
早期的以8字节对齐,现在以16字节对齐的好处可能是

  • 预留空间
  • 一个对象最小是8个字节,以最小倍数翻倍,方便读取,更安全。
 inline 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));

        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
            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);
   }
复制代码

关于3:obj->initInstanceIsa(cls, hasCxxDtor);对cls的一些设置

{ 
    ASSERT(!isTaggedPointer()); 
    
    isa_t newisa(0);

    if (!nonpointer) {
        newisa.setClass(cls, this);
    } else {
        ASSERT(!DisableNonpointerIsa);
        ASSERT(!cls->instancesRequireRawIsa());


#if SUPPORT_INDEXED_ISA
        ASSERT(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        newisa.bits = ISA_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
#   if ISA_HAS_CXX_DTOR_BIT
        newisa.has_cxx_dtor = hasCxxDtor;
#   endif
        newisa.setClass(cls, this);
#endif
        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;
}
复制代码

alloc大致流程如上。

init做了什么呢
- (id)init {
    return _objc_rootInit(self);
}
复制代码

init是一个工厂方法,为开发人员提供一个构造方法的入口

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享