alloc是我们日常开发中经常遇到,下面我们从源码层面分析一下,alloc方法的底层。
准备工作-获取源码
开始探究
我们新建一个类JSPerson
//.h
@interface JSPerson : NSObject
@end
//.m
@implementation JSPerson
@end
复制代码在main方法中初始化JSPerson
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        JSPerson *person = [JSPerson alloc];
        NSLog(@"%@",person);
    }
    return 0;
}
复制代码在JSPerson *person = [JSPerson alloc];这行添加断点运行。
按control键发现断点走到了
KCObjcBuild`objc_alloc:
->  0x100003f44 <+0>: jmpq   *0x40be(%rip)             ; (void *)0x0000000100003f76
复制代码说明这个时候调用了objc_alloc方法,我们打一个objc_alloc的符号断点,继续执行程序,发现断点来到了objc_alloc的源码部分。
// Calls [cls alloc].
id
objc_alloc(Class cls)
{
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}
复制代码我们继续进入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));
}
复制代码我们继续走断点,发现走到了return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));即又调用了alloc方法,也就是说callAlloc也会再次调用。
继续调试这次走到了return _objc_rootAllocWithZone(cls, nil);,断点进入_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);
}
复制代码代码很简单,我们继续跟进到_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 {
        //分配内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }
    ///关联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);
    }
    if (fastpath(!hasCxxCtor)) {
        return obj;
    }
    construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
    return object_cxxConstructFromClass(obj, cls, construct_flags);
}
复制代码_class_createInstanceFromZone方法有三个关键的点,我们下面分别分析:
获取实例大小 size = cls->instanceSize(extraBytes)
内联函数instanceSize的作用是获取实例的大小,对象的大小取决于其ivars(成员变量)的大小。
    // May be unaligned depending on class's ivars.
    uint32_t unalignedInstanceSize() const {
        ASSERT(isRealized());
        return data()->ro()->instanceSize;
    }
    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;
    }
复制代码根据if (size < 16) size = 16;可以看出,对象最小大小为16,这个就是内存对齐的概念,上面的alignedInstanceSize()函数,会继续调用内联函数word_align
// __LP64__
#   define WORD_MASK 7UL
static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
复制代码这里就引入一个概念就是字节对齐。可以看到WORD_MASK=7,它的作用是保证字节的大小为8的倍数。
给对象分配内存空间
    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);
    }
复制代码总结
总结来看alloc的流程图即为下图所示:

























![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)
