shmily-iOS/Mac收藏文章

iOS NSObject.mm源码解析

2017-06-12  本文已影响228人  晨寂

这里是有篇文章对于Obj 对象生成过程进行详细说明的文章,个人感觉很不错
Objc 对象的今生今世


alloc

首先看下alloc,这是从苹果官方源代码objc4/objc4-706/runtime/NSObject.mm下载下来提交到github上的,因为苹果官方页面实在太慢了…
这是NSObject.mm源码的github地址,点击跳转

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

说明一下callAlloc的三个参数

进入 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 (checkNil && !cls) return nil;  
  
#if __OBJC2__  
    if (! cls->ISA()->hasCustomAWZ()) {  
        // No alloc/allocWithZone implementation. Go straight to the allocator.  
        // fixme store hasCustomAWZ in the non-meta class and   
        // add it to canAllocFast's summary  
        if (cls->canAllocFast()) {  
            // No ctors, raw isa, etc. Go straight to the metal.  
            bool dtor = cls->hasCxxDtor();  
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());  
            if (!obj) return callBadAllocHandler(cls);  
            obj->initInstanceIsa(cls, dtor);  
            return obj;  
        }  
        else {  
            // Has ctor or raw isa or something. Use the slower path.  
            id obj = class_createInstance(cls, 0);  
            if (!obj) return callBadAllocHandler(cls);  
            return obj;  
        }  
    }  
#endif  
  
    // No shortcuts available.  
    if (allocWithZone) return [cls allocWithZone:nil];  
    return [cls alloc];  
}

首先 #if __ OBJC2 __ 这个表示object-c 2.0 版本才有的功能

这里代码比较多,我们先看看cls->ISA()->hasCustomAWZ(),源码在这

// objc-runtime-new.h
// class or superclass has default alloc/allocWithZone: implementation
// Note this is is stored in the metaclass.
bool hasCustomAWZ() {
    return ! bits.hasDefaultAWZ();
}
bool hasDefaultAWZ( ) {  
    return data()->flags & RW_HAS_DEFAULT_AWZ;  
}
bool canAllocFast() {
    return false;
}

RW_HAS_DEFAULT_AWZ 这个是用来标示当前的class或者是superclass是否有默认的alloc/allocWithZone。
所以这里hasDefaultAWZ( )方法是用来判断当前class是否有默认的allocWithZone。
这里代码比较绕口,这样改写一下

if (! cls->ISA()->hasCustomAWZ() )
转变 ->
if( bits.hasDefaultAWZ()) )
转变 ->
if( data()->flags & RW_HAS_DEFAULT_AWZ )

这样看就清晰了,这句话就是判断我们或者superclass没有在 重写 alloc / allocWithZone方法,如果我们已经重写,则系统调用我们的方法。鉴于NSZone已经废弃了,所以基本是在判断alloc。
关于NSZone的,可以看我这篇文章的后半部分(NSZone源码解析):https://www.jianshu.com/p/633f2b1c5dd3


另外,可能有人会在源码注意到,canAllocFast和hasDefaultAWZ都是有另外一种实现的

// objc-runtime-new.h
#if FAST_HAS_DEFAULT_AWZ
bool hasDefaultAWZ() {
    return getBit(FAST_HAS_DEFAULT_AWZ);
}
... 
#if FAST_ALLOC
bool canAllocFast() { 
    return bits &; FAST_ALLOC; 
} 
...

这里为什么没有写出来呢?
因为,需要注意这两个方法是有编译条件的

 #if FAST_ALLOC 
 #if FAST_HAS_DEFAULT_AWZ

条件需要有FAST_ALLOC 和 FAST_HAS_DEFAULT_AWZ这两个宏定义,而这两个在 objc-runtime-new.h 有定义

// objc-runtime-new.h
// Values for class_rw_t->flags or class_t->bits
// These flags are optimized for retain/release and alloc/dealloc
// 64-bit stores more of them in class_t->bits to reduce pointer indirection.
#if !__LP64__
...
#elif 1
...

#else 
// summary bit for fast alloc path: !hasCxxCtor and 
// !instancesRequireRawIsa and instanceSize fits into shiftedSize
// hasCxxCtor是判断当前class或者superclass 是否有.cxx_construct构造方法的实现。
// FAST_ALLOC means
//   FAST_HAS_CXX_CTOR is set
//   FAST_REQUIRES_RAW_ISA is not set
//   FAST_SHIFTED_SIZE is not zero
// FAST_ALLOC does NOT check FAST_HAS_DEFAULT_AWZ because that 
// bit is stored on the metaclass.
#define FAST_ALLOC   (1UL<<50)
// class or superclass has default alloc/allocWithZone: implementation
// Note this is is stored in the metaclass.
#define FAST_HAS_DEFAULT_AWZ    (1UL<<48)
#end

首先 if !__ LP64 __ 是处理32位系统的,这里暂时不考虑,然后这里需要注意的是 elif 1,就是else if(1) 的简写!
也就是说,#else 不会被编译了!那么上面两个条件 FAST_ALLOC 和 FAST_HAS_DEFAULT_AWZ就不成立了!


在 objc-runtime-new.h 绕了好多源码,现在再回到 alloc 和 allocWithZone 这两个方法的实现

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

// Replaced by ObjectAlloc
+ (id)allocWithZone:(struct _NSZone *)zone {
    return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}
id _objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
id _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)  
{  
    id obj;  
  
#if __OBJC2__  
    // allocWithZone under __OBJC2__ ignores the zone parameter  
    (void)zone;  
    obj = class_createInstance(cls, 0);  
#else  
    if (!zone || UseGC) {  
        obj = class_createInstance(cls, 0);  
    }  
    else {  
        obj = class_createInstanceFromZone(cls, 0, zone);  
    }  
#endif  
  
    if (!obj) obj = callBadAllocHandler(cls);  
    return obj;  
}
id  class_createInstance(Class cls, size_t extraBytes)
{
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}
static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    if (slowpath(checkNil && !cls)) return nil;

#if __OBJC2__
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        // No alloc/allocWithZone implementation. Go straight to the allocator.
        // fixme store hasCustomAWZ in the non-meta class and 
        // add it to canAllocFast's summary
        if (fastpath(cls->canAllocFast())) {
            // No ctors, raw isa, etc. Go straight to the metal.
            bool dtor = cls->hasCxxDtor();
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            obj->initInstanceIsa(cls, dtor);
            return obj;
        }
        else {
            // Has ctor or raw isa or something. Use the slower path.
            id obj = class_createInstance(cls, 0);
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            return obj;
        }
    }
#endif

    // No shortcuts available.
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}

到这里就可以看明白,alloc 和 allocWithZone 基本是靠这两个方法:class_createInstance 和 initInstanceIsa 进行初始化Objc对象,那么我们接下来再看看这两个方法是干什么的
先看看 initInstanceIsa

//  objc-object.h
inline void objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    assert(!cls->instancesRequireRawIsa());
    assert(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}
inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    assert(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa.cls = cls;
    } else {
        assert(!DisableNonpointerIsa);
        assert(!cls->instancesRequireRawIsa());

        isa_t newisa(0);

#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
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
        isa = newisa;
    }
}

initInstanceIsa 里面是初始化 isa 指针的操作。
再看看class_createInstance

// objc-runtime-new.mm
id class_createInstance(Class cls, size_t extraBytes)
{
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}
id class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
{
    return _class_createInstanceFromZone(cls, extraBytes, zone);
}
static __attribute__((always_inline)) 
id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, 
                              bool cxxConstruct = true, 
                              size_t *outAllocatedSize = nil)
{
    if (!cls) return nil;

    assert(cls->isRealized());

    // Read class's info bits all at once for performance
    bool hasCxxCtor = cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();

    size_t size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (!zone  &&  fast) {
        obj = (id)calloc(1, size);
        if (!obj) return nil;
        obj->initInstanceIsa(cls, hasCxxDtor);
    } 
    else {
        if (zone) {
            obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
        } else {
            obj = (id)calloc(1, size);
        }
        if (!obj) return nil;

        // Use raw pointer isa on the assumption that they might be 
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (cxxConstruct && hasCxxCtor) {
        obj = _objc_constructOrFree(obj, cls);
    }

    return obj;
}

class_createInstance 在初始化内存之后,也是调用initInstanceIsa或者initIsa进行isa指针的设置。
那么就是说 alloc 和 allocWithZone 到最后做的都是同一件事(当然,中间有很多步操作,到时可以再细化描述一下)。

列举下 alloc 整个调用流程

  1. alloc / allocWithZone
  2. class_createInstance / initInstanceIsa
  3. calloc (这里才开始分配内存)
  4. initIsa (初始化isa指针里面的内容)

init

init的代码相对简单,代码里面只是返回self

// NSObject.mm
// Replaced by CF (throws an NSException)  
+ (id)init {   // 类方法
    return (id)self;  
}  
- (id)init {  // 对象方法
    return _objc_rootInit(self);  
}
id _objc_rootInit(id obj)  
{  
    // In practice, it will be hard to rely on this function.  
    // Many classes do not properly chain -init calls.  
    return obj;  
}  

最后列举下OC对象的四种状态:

上一篇 下一篇

猜你喜欢

热点阅读