ios中NSObject的定義
查看蘋(píng)果源碼可看到,蘋(píng)果源碼地址Source Browser
struct objc_object {
? ? Class_Nonnull isa? OBJC_ISA_AVAILABILITY;
};
其中Class為一個(gè)結(jié)構(gòu)體指針typedef struct objc_class *Class;共耍。
objc_class結(jié)構(gòu)體定義為
structobjc_class {
? ? Class_Nonnullisa? OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
? ? Class _Nullable super_class? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? const char*_Nonnullname? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? long version? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? long info? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? long instance_size? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? struct objc_ivar_list *_Nullableivars? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? struct objc_method_list *_Nullable*_NullablemethodLists? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? struct objc_cache *_Nonnullcache? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
? ? struct objc_protocol_list *_Nullableprotocols? ? ? ? ? OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
元類(Meta Class)的定義
isa表示一個(gè)Class對(duì)象的Class,也就是Meta Class
Category實(shí)現(xiàn)原理
查看分類結(jié)構(gòu)體
structobjc_category {
char*category_name;
char*class_name;
struct objc_method_list *instance_methods;
struct objc_method_list *class_methods;
struct objc_protocol_list *protocols;
};
查看objc_method_list結(jié)構(gòu)體
structobjc_method_list {
#if defined(Release3CompatibilityBuild)
? ? ? ? structobjc_method_list *method_next;
#else
structobjc_method_list *obsolete;
#endif
intmethod_count;
#ifdef __alpha__
intspace;
#endif
structobjc_method {
SELmethod_name;
char*method_types;
? ? ? ? ? ? ? ? IMPmethod_imp;
} method_list[1]; /* variable length structure */
};
查看objc_protocol_list結(jié)構(gòu)體
structobjc_protocol_list {
structobjc_protocol_list *next;
intcount;
Protocol *list[1];
};
查看objc_ivar_list的定義
struct objc_ivar_list {
? int ivar_count? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
#ifdef __LP64__
? int space? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
#endif
? /* variable length structure */
? struct objc_ivar ivar_list[1]? ? ? ? ? ? ? ? ? ? ? ? ? ? OBJC2_UNAVAILABLE;
}
methodLists表示方法列表栏尚,它指向objc_method_list結(jié)構(gòu)體的二級(jí)指針,可以動(dòng)態(tài)修改*methodLists的值來(lái)添加成員方法厕宗,也可以動(dòng)態(tài)修改objc_protocol_list來(lái)添加protocol彻亲,也是Category實(shí)現(xiàn)原理,同樣也解釋Category不能添加屬性的原因翻斟。在runtime.h可以看到它的定義: