alloc做了什么

907 阅读3分钟
    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是指向对象的指针,他们(p、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);
}

成员变量是以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;
    }
    
     uint32_t alignedInstanceSize() const {
        //字节对齐
        return word_align(unalignedInstanceSize());
    }
    
    static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
    // (x + 7) & ~7  8字节对齐
   }

关于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大致流程如上。 alloc在汇编的时候会发现先走objc_alloc 截屏2021-06-14 下午3.16.25.png 我们找到源码:

objc_alloc(Class cls)
{
//里面也是调用callAlloc
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}

截屏2021-06-14 下午3.19.10.png 我们在LGPerson初始化的时候打一个断点 在objc_alloc函数中也打一个断点,调用顺序如下:

截屏2021-06-14 下午3.24.44.png alloc和callAlloc方法被调用两次,先调用objc_alloc。 alloc为什么会调用objc_alloc呢,其实是在llvm中做了一层hook,所以是先调用objc_alloc

截屏2021-06-14 下午3.30.37.png 如果是alloc会调用objc_alloc 截屏2021-06-14 下午3.31.24.png 完整的流程图如下:

截屏2021-06-22 上午9.41.36.png

init做了什么呢
- (id)init {
    return _objc_rootInit(self);
}
_objc_rootInit(id obj)
{
    
    return obj;
}

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