日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

深入理解Objective-C:Category

發(fā)布時間:2025/3/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 深入理解Objective-C:Category 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

摘要

無論一個類設(shè)計(jì)的多么完美,在未來的需求演進(jìn)中,都有可能會碰到一些無法預(yù)測的情況。那怎么擴(kuò)展已有的類呢?一般而言,繼承和組合是不錯的選擇。但是在Objective-C 2.0中,又提供了category這個語言特性,可以動態(tài)地為已有類添加新行為。如今category已經(jīng)遍布于Objective-C代碼的各個角落,從Apple官方的framework到各個開源框架,從功能繁復(fù)的大型APP到簡單的應(yīng)用,catagory無處不在。本文對category做了比較全面的整理,希望對讀者有所裨益。

簡介

本文作者來自美團(tuán)酒店旅游事業(yè)群iOS研發(fā)組。我們致力于創(chuàng)造價值、提升效率、追求卓越。歡迎大家加入我們(簡歷請發(fā)送到郵箱majia03@meituan.com)。
本文系學(xué)習(xí)Objective-C的runtime源碼時整理所成,主要剖析了category在runtime層的實(shí)現(xiàn)原理以及和category相關(guān)的方方面面,內(nèi)容包括:

  • 初入寶地-category簡介
  • 連類比事-category和extension
  • 挑燈細(xì)覽-category真面目
  • 追本溯源-category如何加載
  • 旁枝末葉-category和+load方法
  • 觸類旁通-category和方法覆蓋
  • 更上一層-category和關(guān)聯(lián)對象

1、初入寶地-category簡介

category是Objective-C 2.0之后添加的語言特性,category的主要作用是為已經(jīng)存在的類添加方法。除此之外,apple還推薦了category的另外兩個使用場景1

  • 可以把類的實(shí)現(xiàn)分開在幾個不同的文件里面。這樣做有幾個顯而易見的好處,a)可以減少單個文件的體積 b)可以把不同的功能組織到不同的category里 c)可以由多個開發(fā)者共同完成一個類 d)可以按需加載想要的category 等等。
  • 聲明私有方法

不過除了apple推薦的使用場景,廣大開發(fā)者腦洞大開,還衍生出了category的其他幾個使用場景:

  • 模擬多繼承
  • 把framework的私有方法公開

Objective-C的這個語言特性對于純動態(tài)語言來說可能不算什么,比如javascript,你可以隨時為一個“類”或者對象添加任意方法和實(shí)例變量。但是對于不是那么“動態(tài)”的語言而言,這確實(shí)是一個了不起的特性。

2、連類比事-category和extension

extension看起來很像一個匿名的category,但是extension和有名字的category幾乎完全是兩個東西。 extension在編譯期決議,它就是類的一部分,在編譯期和頭文件里的@interface以及實(shí)現(xiàn)文件里的@implement一起形成一個完整的類,它伴隨類的產(chǎn)生而產(chǎn)生,亦隨之一起消亡。extension一般用來隱藏類的私有信息,你必須有一個類的源碼才能為一個類添加extension,所以你無法為系統(tǒng)的類比如NSString添加extension。(詳見2)

但是category則完全不一樣,它是在運(yùn)行期決議的。
就category和extension的區(qū)別來看,我們可以推導(dǎo)出一個明顯的事實(shí),extension可以添加實(shí)例變量,而category是無法添加實(shí)例變量的(因?yàn)樵谶\(yùn)行期,對象的內(nèi)存布局已經(jīng)確定,如果添加實(shí)例變量就會破壞類的內(nèi)部布局,這對編譯型語言來說是災(zāi)難性的)。

3、挑燈細(xì)覽-category真面目

我們知道,所有的OC類和對象,在runtime層都是用struct表示的,category也不例外,在runtime層,category用結(jié)構(gòu)體category_t(在objc-runtime-new.h中可以找到此定義),它包含了
1)、類的名字(name)
2)、類(cls)
3)、category中所有給類添加的實(shí)例方法的列表(instanceMethods)
4)、category中所有添加的類方法的列表(classMethods)
5)、category實(shí)現(xiàn)的所有協(xié)議的列表(protocols)
6)、category中添加的所有屬性(instanceProperties)

typedef struct category_t {const char *name;classref_t cls;struct method_list_t *instanceMethods;struct method_list_t *classMethods;struct protocol_list_t *protocols;struct property_list_t *instanceProperties; } category_t;

從category的定義也可以看出category的可為(可以添加實(shí)例方法,類方法,甚至可以實(shí)現(xiàn)協(xié)議,添加屬性)和不可為(無法添加實(shí)例變量)。
ok,我們先去寫一個category看一下category到底為何物:

MyClass.h:

#import <Foundation/Foundation.h>@interface MyClass : NSObject- (void)printName;@end@interface MyClass(MyAddition)@property(nonatomic, copy) NSString *name;- (void)printName;@end

MyClass.m:

#import "MyClass.h"@implementation MyClass- (void)printName {NSLog(@"%@",@"MyClass"); }@end@implementation MyClass(MyAddition)- (void)printName {NSLog(@"%@",@"MyAddition"); }@end

我們使用clang的命令去看看category到底會變成什么:

clang -rewrite-objc MyClass.m

好吧,我們得到了一個3M大小,10w多行的.cpp文件(這絕對是Apple值得吐槽的一點(diǎn)),我們忽略掉所有和我們無關(guān)的東西,在文件的最后,我們找到了如下代碼片段:

static struct /*_method_list_t*/ { unsigned int entsize; // sizeof(struct _objc_method) unsigned int method_count; struct _objc_method method_list[1]; } _OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition __attribute__ ((used, section ("__DATA,__objc_const"))) = { sizeof(_objc_method), 1, {{(struct objc_selector *)"printName", "v16@0:8", (void *)_I_MyClass_MyAddition_printName}} };static struct /*_prop_list_t*/ { unsigned int entsize; // sizeof(struct _prop_t) unsigned int count_of_properties; struct _prop_t prop_list[1]; } _OBJC_$_PROP_LIST_MyClass_$_MyAddition __attribute__ ((used, section ("__DATA,__objc_const"))) = { sizeof(_prop_t), 1, {{"name","T@\"NSString\",C,N"}} };extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_MyClass;static struct _category_t _OBJC_$_CATEGORY_MyClass_$_MyAddition __attribute__ ((used, section ("__DATA,__objc_const"))) = { "MyClass", 0, // &OBJC_CLASS_$_MyClass, (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition, 0, 0, (const struct _prop_list_t *)&_OBJC_$_PROP_LIST_MyClass_$_MyAddition, }; static void OBJC_CATEGORY_SETUP_$_MyClass_$_MyAddition(void ) { _OBJC_$_CATEGORY_MyClass_$_MyAddition.cls = &OBJC_CLASS_$_MyClass; } #pragma section(".objc_inithooks$B", long, read, write) __declspec(allocate(".objc_inithooks$B")) static void *OBJC_CATEGORY_SETUP[] = { (void *)&OBJC_CATEGORY_SETUP_$_MyClass_$_MyAddition, }; static struct _class_t *L_OBJC_LABEL_CLASS_$ [1] __attribute__((used, section ("__DATA, __objc_classlist,regular,no_dead_strip")))= { &OBJC_CLASS_$_MyClass, }; static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = { &OBJC_CLASS_$_MyClass, }; static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= { &_OBJC_$_CATEGORY_MyClass_$_MyAddition, };

我們可以看到,
1)、首先編譯器生成了實(shí)例方法列表OBJC$_CATEGORY_INSTANCE_METHODSMyClass$_MyAddition和屬性列表OBJC$_PROP_LISTMyClass$_MyAddition,兩者的命名都遵循了公共前綴+類名+category名字的命名方式,而且實(shí)例方法列表里面填充的正是我們在MyAddition這個category里面寫的方法printName,而屬性列表里面填充的也正是我們在MyAddition里添加的name屬性。還有一個需要注意到的事實(shí)就是category的名字用來給各種列表以及后面的category結(jié)構(gòu)體本身命名,而且有static來修飾,所以在同一個編譯單元里我們的category名不能重復(fù),否則會出現(xiàn)編譯錯誤。
2)、其次,編譯器生成了category本身OBJC$_CATEGORYMyClass$_MyAddition,并用前面生成的列表來初始化category本身。
3)、最后,編譯器在DATA段下的objc_catlist section里保存了一個大小為1的category_t的數(shù)組L_OBJC_LABELCATEGORY$(當(dāng)然,如果有多個category,會生成對應(yīng)長度的數(shù)組^_^),用于運(yùn)行期category的加載。
到這里,編譯器的工作就接近尾聲了,對于category在運(yùn)行期怎么加載,我們下節(jié)揭曉。

4、追本溯源-category如何加載

我們知道,Objective-C的運(yùn)行是依賴OC的runtime的,而OC的runtime和其他系統(tǒng)庫一樣,是OS X和iOS通過dyld動態(tài)加載的。
想了解更多dyld地同學(xué)可以移步這里(3)。

對于OC運(yùn)行時,入口方法如下(在objc-os.mm文件中):

void _objc_init(void) {static bool initialized = false;if (initialized) return;initialized = true;// fixme defer initialization until an objc-using image is found?environ_init();tls_init();lock_init();exception_init();// Register for unmap first, in case some +load unmaps something_dyld_register_func_for_remove_image(&unmap_image);dyld_register_image_state_change_handler(dyld_image_state_bound,1/*batch*/, &map_images);dyld_register_image_state_change_handler(dyld_image_state_dependents_initialized, 0/*not batch*/, &load_images); }

category被附加到類上面是在map_images的時候發(fā)生的,在new-ABI的標(biāo)準(zhǔn)下,_objc_init里面的調(diào)用的map_images最終會調(diào)用objc-runtime-new.mm里面的_read_images方法,而在_read_images方法的結(jié)尾,有以下的代碼片段:

// Discover categories. for (EACH_HEADER) {category_t **catlist =_getObjc2CategoryList(hi, &count);for (i = 0; i < count; i++) {category_t *cat = catlist[i];class_t *cls = remapClass(cat->cls);if (!cls) {// Category's target class is missing (probably weak-linked).// Disavow any knowledge of this category.catlist[i] = NULL;if (PrintConnecting) {_objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with ""missing weak-linked target class",cat->name, cat);}continue;}// Process this category. // First, register the category with its target class. // Then, rebuild the class's method lists (etc) if // the class is realized. BOOL classExists = NO;if (cat->instanceMethods || cat->protocols || cat->instanceProperties){addUnattachedCategoryForClass(cat, cls, hi);if (isRealized(cls)) {remethodizeClass(cls);classExists = YES;}if (PrintConnecting) {_objc_inform("CLASS: found category -%s(%s) %s",getName(cls), cat->name,classExists ? "on existing class" : "");}}if (cat->classMethods || cat->protocols /* || cat->classProperties */){addUnattachedCategoryForClass(cat, cls->isa, hi);if (isRealized(cls->isa)) {remethodizeClass(cls->isa);}if (PrintConnecting) {_objc_inform("CLASS: found category +%s(%s)",getName(cls), cat->name);}}}}

首先,我們拿到的catlist就是上節(jié)中講到的編譯器為我們準(zhǔn)備的category_t數(shù)組,關(guān)于是如何加載catlist本身的,我們暫且不表,這和category本身的關(guān)系也不大,有興趣的同學(xué)可以去研究以下Apple的二進(jìn)制格式和load機(jī)制。
略去PrintConnecting這個用于log的東西,這段代碼很容易理解:
1)、把category的實(shí)例方法、協(xié)議以及屬性添加到類上
2)、把category的類方法和協(xié)議添加到類的metaclass上

值得注意的是,在代碼中有一小段注釋 /?|| cat->classProperties?/,看來蘋果有過給類添加屬性的計(jì)劃啊。
ok,我們接著往里看,category的各種列表是怎么最終添加到類上的,就拿實(shí)例方法列表來說吧:
在上述的代碼片段里,addUnattachedCategoryForClass只是把類和category做一個關(guān)聯(lián)映射,而remethodizeClass才是真正去處理添加事宜的功臣。

static void remethodizeClass(class_t *cls) {category_list *cats;BOOL isMeta;rwlock_assert_writing(&runtimeLock);isMeta = isMetaClass(cls);// Re-methodizing: check for more categoriesif ((cats = unattachedCategoriesForClass(cls))) {chained_property_list *newproperties;const protocol_list_t **newprotos;if (PrintConnecting) {_objc_inform("CLASS: attaching categories to class '%s' %s",getName(cls), isMeta ? "(meta)" : "");}// Update methods, properties, protocolsBOOL vtableAffected = NO;attachCategoryMethods(cls, cats, &vtableAffected);newproperties = buildPropertyList(NULL, cats, isMeta);if (newproperties) {newproperties->next = cls->data()->properties;cls->data()->properties = newproperties;}newprotos = buildProtocolList(cats, NULL, cls->data()->protocols);if (cls->data()->protocols && cls->data()->protocols != newprotos) {_free_internal(cls->data()->protocols);}cls->data()->protocols = newprotos;_free_internal(cats);// Update method caches and vtablesflushCaches(cls);if (vtableAffected) flushVtables(cls);} }

而對于添加類的實(shí)例方法而言,又會去調(diào)用attachCategoryMethods這個方法,我們?nèi)タ聪耡ttachCategoryMethods:

static void attachCategoryMethods(class_t *cls, category_list *cats,BOOL *inoutVtablesAffected) {if (!cats) return;if (PrintReplacedMethods) printReplacements(cls, cats);BOOL isMeta = isMetaClass(cls);method_list_t **mlists = (method_list_t **)_malloc_internal(cats->count * sizeof(*mlists));// Count backwards through cats to get newest categories firstint mcount = 0;int i = cats->count;BOOL fromBundle = NO;while (i--) {method_list_t *mlist = cat_method_list(cats->list[i].cat, isMeta);if (mlist) {mlists[mcount++] = mlist;fromBundle |= cats->list[i].fromBundle;}}attachMethodLists(cls, mlists, mcount, NO, fromBundle, inoutVtablesAffected);_free_internal(mlists);}

attachCategoryMethods做的工作相對比較簡單,它只是把所有category的實(shí)例方法列表拼成了一個大的實(shí)例方法列表,然后轉(zhuǎn)交給了attachMethodLists方法(我發(fā)誓,這是本節(jié)我們看的最后一段代碼了^_^),這個方法有點(diǎn)長,我們只看一小段:

for (uint32_t m = 0;(scanForCustomRR || scanForCustomAWZ) && m < mlist->count;m++){SEL sel = method_list_nth(mlist, m)->name;if (scanForCustomRR && isRRSelector(sel)) {cls->setHasCustomRR();scanForCustomRR = false;} else if (scanForCustomAWZ && isAWZSelector(sel)) {cls->setHasCustomAWZ();scanForCustomAWZ = false;}}// Fill method list arraynewLists[newCount++] = mlist;...// Copy old methods to the method list arrayfor (i = 0; i < oldCount; i++) {newLists[newCount++] = oldLists[i];}

需要注意的有兩點(diǎn):
1)、category的方法沒有“完全替換掉”原來類已經(jīng)有的方法,也就是說如果category和原來類都有methodA,那么category附加完成之后,類的方法列表里會有兩個methodA
2)、category的方法被放到了新方法列表的前面,而原來類的方法被放到了新方法列表的后面,這也就是我們平常所說的category的方法會“覆蓋”掉原來類的同名方法,這是因?yàn)檫\(yùn)行時在查找方法的時候是順著方法列表的順序查找的,它只要一找到對應(yīng)名字的方法,就會罷休^_^,殊不知后面可能還有一樣名字的方法。

5、旁枝末葉-category和+load方法

我們知道,在類和category中都可以有+load方法,那么有兩個問題:
1)、在類的+load方法調(diào)用的時候,我們可以調(diào)用category中聲明的方法么?
2)、這么些個+load方法,調(diào)用順序是咋樣的呢?
鑒于上述幾節(jié)我們看的代碼太多了,對于這兩個問題我們先來看一點(diǎn)直觀的:

我們的代碼里有MyClass和MyClass的兩個category (Category1和Category2),MyClass和兩個category都添加了+load方法,并且Category1和Category2都寫了MyClass的printName方法。
在Xcode中點(diǎn)擊Edit Scheme,添加如下兩個環(huán)境變量(可以在執(zhí)行l(wèi)oad方法以及加載category的時候打印log信息,更多的環(huán)境變量選項(xiàng)可參見objc-private.h):

運(yùn)行項(xiàng)目,我們會看到控制臺打印很多東西出來,我們只找到我們想要的信息,順序如下:

objc[1187]: REPLACED: -[MyClass printName] by category Category1
objc[1187]: REPLACED: -[MyClass printName] by category Category2
.
.
.
objc[1187]: LOAD: class 'MyClass' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[1187]: LOAD: +[MyClass load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category1) load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category2) load]

所以,對于上面兩個問題,答案是很明顯的:
1)、可以調(diào)用,因?yàn)楦郊觕ategory到類的工作會先于+load方法的執(zhí)行
2)、+load的執(zhí)行順序是先類,后category,而category的+load執(zhí)行順序是根據(jù)編譯順序決定的。
目前的編譯順序是這樣的:

我們調(diào)整一個Category1和Category2的編譯順序,run。ok,我們可以看到控制臺的輸出順序變了:

objc[1187]: REPLACED: -[MyClass printName] by category Category2
objc[1187]: REPLACED: -[MyClass printName] by category Category1
.
.
.
objc[1187]: LOAD: class 'MyClass' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[1187]: LOAD: +[MyClass load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category2) load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category1) load]

雖然對于+load的執(zhí)行順序是這樣,但是對于“覆蓋”掉的方法,則會先找到最后一個編譯的category里的對應(yīng)方法。
這一節(jié)我們只是用很直觀的方式得到了問題的答案,有興趣的同學(xué)可以繼續(xù)去研究一下OC的運(yùn)行時代碼。

6、觸類旁通-category和方法覆蓋

鑒于上面幾節(jié)我們已經(jīng)把原理都講了,這一節(jié)只有一個問題:
怎么調(diào)用到原來類中被category覆蓋掉的方法?
對于這個問題,我們已經(jīng)知道category其實(shí)并不是完全替換掉原來類的同名方法,只是category在方法列表的前面而已,所以我們只要順著方法列表找到最后一個對應(yīng)名字的方法,就可以調(diào)用原來類的方法:

Class currentClass = [MyClass class]; MyClass *my = [[MyClass alloc] init];if (currentClass) {unsigned int methodCount;Method *methodList = class_copyMethodList(currentClass, &methodCount);IMP lastImp = NULL;SEL lastSel = NULL;for (NSInteger i = 0; i < methodCount; i++) {Method method = methodList[i];NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(method)) encoding:NSUTF8StringEncoding];if ([@"printName" isEqualToString:methodName]) {lastImp = method_getImplementation(method);lastSel = method_getName(method);}}typedef void (*fn)(id,SEL);if (lastImp != NULL) {fn f = (fn)lastImp;f(my,lastSel);}free(methodList); }

7、更上一層-category和關(guān)聯(lián)對象

如上所見,我們知道在category里面是無法為category添加實(shí)例變量的。但是我們很多時候需要在category中添加和對象關(guān)聯(lián)的值,這個時候可以求助關(guān)聯(lián)對象來實(shí)現(xiàn)。

MyClass+Category1.h:

#import "MyClass.h"@interface MyClass (Category1)@property(nonatomic,copy) NSString *name;@end

MyClass+Category1.m:

#import "MyClass+Category1.h" #import <objc/runtime.h>@implementation MyClass (Category1)+ (void)load {NSLog(@"%@",@"load in Category1"); }- (void)setName:(NSString *)name {objc_setAssociatedObject(self,"name",name,OBJC_ASSOCIATION_COPY); }- (NSString*)name {NSString *nameObject = objc_getAssociatedObject(self, "name");return nameObject; }@end

但是關(guān)聯(lián)對象又是存在什么地方呢? 如何存儲? 對象銷毀時候如何處理關(guān)聯(lián)對象呢?
我們?nèi)シ幌聄untime的源碼,在objc-references.mm文件中有個方法_object_set_associative_reference:

void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {// retain the new value (if any) outside the lock.ObjcAssociation old_association(0, nil);id new_value = value ? acquireValue(value, policy) : nil;{AssociationsManager manager;AssociationsHashMap &associations(manager.associations());disguised_ptr_t disguised_object = DISGUISE(object);if (new_value) {// break any existing association.AssociationsHashMap::iterator i = associations.find(disguised_object);if (i != associations.end()) {// secondary table existsObjectAssociationMap *refs = i->second;ObjectAssociationMap::iterator j = refs->find(key);if (j != refs->end()) {old_association = j->second;j->second = ObjcAssociation(policy, new_value);} else {(*refs)[key] = ObjcAssociation(policy, new_value);}} else {// create the new association (first time).ObjectAssociationMap *refs = new ObjectAssociationMap;associations[disguised_object] = refs;(*refs)[key] = ObjcAssociation(policy, new_value);_class_setInstancesHaveAssociatedObjects(_object_getClass(object));}} else {// setting the association to nil breaks the association.AssociationsHashMap::iterator i = associations.find(disguised_object);if (i != associations.end()) {ObjectAssociationMap *refs = i->second;ObjectAssociationMap::iterator j = refs->find(key);if (j != refs->end()) {old_association = j->second;refs->erase(j);}}}}// release the old value (outside of the lock).if (old_association.hasValue()) ReleaseValue()(old_association); }

我們可以看到所有的關(guān)聯(lián)對象都由AssociationsManager管理,而AssociationsManager定義如下:

class AssociationsManager {static OSSpinLock _lock;static AssociationsHashMap *_map; // associative references: object pointer -> PtrPtrHashMap. public:AssociationsManager() { OSSpinLockLock(&_lock); }~AssociationsManager() { OSSpinLockUnlock(&_lock); }AssociationsHashMap &associations() {if (_map == NULL)_map = new AssociationsHashMap();return *_map;} };

AssociationsManager里面是由一個靜態(tài)AssociationsHashMap來存儲所有的關(guān)聯(lián)對象的。這相當(dāng)于把所有對象的關(guān)聯(lián)對象都存在一個全局map里面。而map的的key是這個對象的指針地址(任意兩個不同對象的指針地址一定是不同的),而這個map的value又是另外一個AssociationsHashMap,里面保存了關(guān)聯(lián)對象的kv對。
而在對象的銷毀邏輯里面,見objc-runtime-new.mm:

void *objc_destructInstance(id obj) {if (obj) {Class isa_gen = _object_getClass(obj);class_t *isa = newcls(isa_gen);// Read all of the flags at once for performance.bool cxx = hasCxxStructors(isa);bool assoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen);// This order is important.if (cxx) object_cxxDestruct(obj);if (assoc) _object_remove_assocations(obj);if (!UseGC) objc_clear_deallocating(obj);}return obj; }

嗯,runtime的銷毀對象函數(shù)objc_destructInstance里面會判斷這個對象有沒有關(guān)聯(lián)對象,如果有,會調(diào)用_object_remove_assocations做關(guān)聯(lián)對象的清理工作。

后記

正如侯捷先生所講-“源碼面前,了無秘密”,Apple的Cocoa Touch框架雖然并不開源,但是Objective-C的runtime和Core Foundation卻是完全開放源碼的(在http://www.opensource.apple.com/tarballs/可以下載到全部的開源代碼)。
本系列runtime源碼學(xué)習(xí)將會持續(xù)更新,意猶未盡的同學(xué)可以自行到上述網(wǎng)站下載源碼學(xué)習(xí)。行筆簡陋,如有錯誤,望指正。


from:?http://tech.meituan.com/DiveIntoCategory.html

總結(jié)

以上是生活随笔為你收集整理的深入理解Objective-C:Category的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。