runtime相关L的iOSObjective-C Runtime

Objective-C的runtime机制01-数据结构和内部关

2016-05-28  本文已影响1498人  qiushuitian

上一篇:Objective-C的runtime机制00-概述

那么,OC的对象在runtime的时候会是个什么样子的呢?

runtime中的数据结构

有源码有真相

以下是我摘自runtime源码中的数据结构定义. 我看的版本是 objc4-680

//-------- [file:objc-runtime-new.h] --------
struct objc_class : objc_object {
    // Class ISA;
    Class superclass;
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
    ......
}

//-------- [file:objc-private.h] --------
typedef struct objc_class *Class;
typedef struct objc_object *id;

struct objc_object {
private:
    isa_t isa;
    ......
}

union isa_t 
{
    ......
    Class cls;
    uintptr_t bits;
    ......
}

解读

类对象/元类对象

苹果搞出这么一些乱七八糟的数据结构,那么又是怎么样用这些数据结构搭建OC运行时环境的呢?

描述半天感觉很晕乎,他们说看这张图就清晰多了。虚线 isa指针,实线superclass。


上面部分静态的描述了一下runtime中有哪些对象,他们的关系怎么样。下面动态的描述一下。

为嘛搞那么复杂

C语言不是动态语言。OC作为C的超集,要实现动态,就要把类的描述之类的东西从编译阶段挪到运行阶段。那么在运行阶段,就需要有类对象(class object),元类对象(metaclass object)等等对象化的东西来处理OC类的信息。runtime就这么玩的。

举个例子

DJObject 继承于BaseObject, BaseObject继承于NSObject

//  BaseObject.h
@interface BaseObject : NSObject
@end

// DJObject.h
@interface DJObject : BaseObject
@end

// 比如在代码中造了个对象
DJObject * djObj = [DJObject new];

那么,这些结构就是这样子的:


运行时图

写到这里,基本上runtime的内部架构是清楚了。后面的文章将看看runtime是怎么实现Objective-C的各种机制的。

吐槽一下

网络上贴的各种文章对runtime的结构的摘录,随便摘录了一下就开始说:

//他们在objc.h文件中摘录了这样的一段数据结构。
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};

//他们在runtime.h文件中摘录了这样的一段数据结构。
struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class super_class                                    OBJC2_UNAVAILABLE;
    const char *name                                         OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list *ivars                             OBJC2_UNAVAILABLE;
    struct objc_method_list **methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache *cache                                 OBJC2_UNAVAILABLE;
    struct objc_protocol_list *protocols                     OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;
#if !defined(OBJC_ISA_AVAILABILITY)
#   if __OBJC2__
#       define OBJC_ISA_AVAILABILITY  __attribute__((deprecated))
#   else
#       define OBJC_ISA_AVAILABILITY  /* still available */
#   endif
#endif

就是说,在oc2.0的版本中,这个属性是不推荐的。实际上在2.0的OC层,我们是无法访问isa指针的,所以让人看这个定义是很迷惑的。

下一篇: Objective-C的runtime机制02-消息机制

参考文章

Objective-C对象之类对象和元类对象(一)
Objective-C Runtime 运行时之一:类与对象
刨根问底Objective-C Runtime(2)- Object & Class & Meta Class

上一篇 下一篇

猜你喜欢

热点阅读