iOS NSObject.mm源码解析

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


我把源码从苹果官方上下载并提交到github上的,因为苹果官方页面实在太慢了…
这是NSObject.mm源码的github地址,点击跳转


alloc

首先看下alloc

//  objc4/objc4-706/runtime/NSObject.mm
+ (id)alloc {  
    return _objc_rootAlloc(self);  
}
id _objc_rootAlloc(Class cls)  
{  
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);  
}

说明一下callAlloc的三个参数

  • cls:类信息(如NSString)
  • checkNil:是否需要检查cls为不为nil
  • allocWithZone:是否使用NSZone,如果直接调用alloc的话,系统会在默认的NSZone里面分配内存。

进入 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源码解析)://www.greatytc.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对象的四种状态:

  • 创建并持有对象:alloc init
  • 持有对象:retain、copy
  • 释放对象:release
  • 废弃对象:dealloc
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容