美文网首页
alloc底层源码探索

alloc底层源码探索

作者: Y丶舜禹 | 来源:发表于2020-09-05 22:09 被阅读0次
前言

作为一个iOS开发人员,我们基本每天都要与alloc,init打交道,但是你知道他们的底层到底做了什么吗?今天我们就一起探索一下

资料下载

objc781源码下载

alloc原理探索

常用的探索手法主要有以下四种
  • 断点跟进 control + in 方法
  • Symbolic Breakpoint 符号断点:libobjc.A.dylib`+[NSObject alloc] 或者全局搜索alloc {
  • 菜单Debug -> Debug Workflow -> Always show Disassembly 查看汇编代码
  • 源码跟进

我们直接调试源码,这样可以看的更加直观

objc4-781源码NSObject.mm类中,废话不多说我们直接上代码

alloc源码
+ (id)alloc {
    return _objc_rootAlloc(self);
}
_objc_rootAlloc
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
callAlloc
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
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));
}

_objc_rootAllocWithZone
NEVER_INLINE
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;
    // 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;
    }

    // 3: ?
    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);
}

以上就是alloc的全部调用实现,有兴趣的可以自己亲自调试一下,还是挺有乐趣的。

小知识: init方法和new方法

// Replaced by CF (throws an NSException)
+ (id)init {
    return (id)self;
}

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

上图可看出new方法是由 (alloc + init)方法构成,不过笔者还是建议使用 (alloc + init),不然如果我们重写了init方法的话,new是不会调用init的,这点也是需要注意的。

相关文章

网友评论

      本文标题:alloc底层源码探索

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