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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

category-内部原理、运用场景、特点

發(fā)布時間:2023/12/18 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 category-内部原理、运用场景、特点 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我們講解的category分為三個部分:

1:怎么用:運用場景

2:不能用:爭議性的特點:能做什么不能做什么

3:原因:內(nèi)部原理


前言:

無論一個類設計的多么完美,在未來的需求演進中,都有可能會碰到一些無法預測的情況。那怎么擴展已有的類呢?一般而言,繼承和組合是不錯的選擇。但是在Objective-C 2.0中,又提供了category這個語言特性,可以動態(tài)地為已有類添加新行為。Objective-C的這個語言特性對于純動態(tài)語言來說可能不算什么,比如javascript,你可以隨時為一個“類”或者對象添加任意方法和實例變量。但是對于不是那么“動態(tài)”的語言而言,這確實是一個了不起的特性。



1:怎么用:運用場景

1.1:主要作用是為已經(jīng)存在的類添加方法。

想要收集每個頁面的啟動時間:項目中已經(jīng)有上百個頁面了,如果一個一個的加,浪費時間不說,以后增加了新頁面,還需要添加方法。

解決方法:

我們可以發(fā)現(xiàn)頁面都繼承了UIViewController,想要在每個頁面都執(zhí)行的代碼,可以寫在這些頁面的父類中。我們可以把代碼寫在UIViewController中,使用分類(category)。

1.2 :分類

一個類中的代碼非常多,如果超過1000多行,那么在翻閱的時候也會覺得很困難,但是繼承下來,再使用的時候,只能集成子類,而且方法比較多,想要直接分散開來,不是特別容易,所以可以采取分類的方式,把想通類型的代碼加載在一起。

好處:可以把類的實現(xiàn)分開在幾個不同的文件里面。這樣做有幾個顯而易見的好處,

?a)可以減少單個文件的體積

?b)可以把不同的功能組織到不同的category里

?c)可以由多個開發(fā)者共同完成一個類

?d)可以按需加載想要的category 等等。

并且 還可以按照需要加載想要的category。


1.3:引用父類未公開方法

比如父類 XSDLabel:

// XSDLabel.h #import <UIKit/UIKit.h>@interface XSDLabel : UILabel@end // XSDLabel.m #import "XSDLabel.h"@implementation XSDLabel - (void)giveTextRandomColor {self.textColor = [UIColor orangeColor]; } @end

XSDLabel1繼承自XSDLabel:

#import <UIKit/UIKit.h> #import "XSDLabel.h" @interface XSDLabel1 : XSDLabel@end

現(xiàn)在需要在設置text時,同時設置文字顏色,調(diào)用父類的giveTextRandomColor:

#import "XSDLabel1.h"@implementation XSDLabel1- (void)setText:(NSString *)text {[super setText:text];[self giveTextRandomColor]; }@end

直接編譯會報錯:


編譯器提示找不到父類的方法

在子類中聲明父類類別后,即可通過編譯:

#import "XSDLabel1.h"@interface XSDLabel (private) - (void)giveTextRandomColor; @end@implementation XSDLabel1- (void)setText:(NSString *)text {[super setText:text];[self giveTextRandomColor]; }@end

類別名private是任意的,但不可以缺省。

請不要亂來:蘋果官方會拒絕使用系統(tǒng)私有API的應用上架,因此即使學會了如何調(diào)用私有方法,在遇到調(diào)用其它類的私有方法時,要謹慎處理,盡量用其它方法替代。


1.4:聲明私有方法

1.5:模擬多繼承

1.6:把framework的私有方法公開


2:不能用:爭議性的特點:能做什么不能做什么

(如果看下面簡單的原因解釋不明白的 可以繼續(xù)向下面看category的內(nèi)部原理,講的比較細致)


2.1:只能添加方法,不能為一個類動態(tài)的添加成員變量,可以給類動態(tài)增加方法和屬性。

在類別中聲明的屬性,將無法存取,

原因:因為分類是動態(tài)時,此時,類的框架已經(jīng)實現(xiàn),屬性列表里并沒有給動態(tài)添加的屬性賦值。其次并不是不能添加屬性,而是添加一個Property,系統(tǒng)不會自動給他創(chuàng)建set和get方法,運用runtime:objc_setAssociatedObjectobjc_getAssociatedObject給分類創(chuàng)建set和get方法。。

因為方法和屬性并不“屬于”類實例,而成員變量“屬于”類實例。我們所說的“類實例”概念,指的是一塊內(nèi)存區(qū)域,包含了isa指針和所有的成員變量。所以假如允許動態(tài)修改類成員變量布局,已經(jīng)創(chuàng)建出的類實例就不符合類定義了,變成了無效對象。但方法定義是在objc_class中管理的,不管如何增刪類方法,都不影響類實例的內(nèi)存布局,已經(jīng)創(chuàng)建出的類實例仍然可正常使用。具體請看這里


2.2:類別中的方法,會“覆蓋”父類中的同名方法,無法再調(diào)用父類中的方法(因為類別中無法使用super)

為防止意外覆蓋,總是應該給類別加上前綴。

原因:這個不是覆蓋,因為所有的類的方法和分類的方法,都會在類的方法列表中存在,類自己的是會先放進去,類別是動態(tài)添加的所以是后放入的,根據(jù)取方法的順序,后進先出,而系統(tǒng)的特性是,只要找到了相同的方法便不再繼續(xù)尋找,所以如果分類實現(xiàn)了本類的方法,會先調(diào)用分類的,如果有多個分類同時實現(xiàn),那要看編譯的時候哪個方法最后放入。

Category 可以實現(xiàn)原始類的方法:

具體原因:

1).重寫原生方法之后 會覆蓋掉原有的方法,因為在OC中是runtime執(zhí)行 且方法執(zhí)行時僅僅有一個方法會被執(zhí)行,除loadView會先執(zhí)行原生方法然后執(zhí)行category外 其他都是執(zhí)行category重寫的方法體。

2).當多個地方對系統(tǒng)本身的方法進行了重寫 則執(zhí)行時系統(tǒng)無法知道執(zhí)行哪一個方法。

3).category的出現(xiàn)只是為了擴展原有的類。如果需要重寫 使用繼承吧。


2.3:不同文件中的同名類別,同名方法,不會報錯,實際執(zhí)行的方法以最后一個加載的文件為準,因此使用前綴防止類別人互相覆蓋。


2.4:分類中可以訪問原來類中的成員變量,但是只能訪問@protect和@public形式的變量。如果想要訪問本類中的私有變量,分類和子類一樣,只能通過方法來訪問。


2.5:category和Extension延展不同。

原因:

extension看起來很像一個匿名的category,但是extension和有名字的category幾乎完全是兩個東西。 extension在編譯期決議,它就是類的一部分,在編譯期和頭文件里的@interface以及實現(xiàn)文件里的@implement一起形成一個完整的類,它伴隨類的產(chǎn)生而產(chǎn)生,亦隨之一起消亡。extension一般用來隱藏類的私有信息,你必須有一個類的源碼才能為一個類添加extension,所以你無法為系統(tǒng)的類比如NSString添加extension。但是category則完全不一樣,它是在運行期決議的。就category和extension的區(qū)別來看,我們可以推導出一個明顯的事實,extension可以添加實例變量,而category是無法添加實例變量的(因為在運行期,對象的內(nèi)存布局已經(jīng)確定,如果添加實例變量就會破壞類的內(nèi)部布局,這對編譯型語言來說是災難性的)。

想知道詳細區(qū)別的,請看這里

小記:

我自己寫了一個分類,通過runtime來獲取類的方法和屬性,發(fā)現(xiàn)分類方法和本類方法在一個方法列表,引用不引用都在,只是引用之后,在類里就可以用這個分類的方法。不引用的話,編譯器找不到方法,就會報錯



3:原因:內(nèi)部原理

現(xiàn)在講解最重要的內(nèi)部原理,上面的有爭議的特性還沒有徹底明白為啥的 可以細細看下面。


3.1:category真面目

我們知道,所有的OC類和對象,在runtime層都是用struct表示的,category也不例外,在runtime層,category用結(jié)構(gòu)體category_t(在objc-runtime-new.h中可以找到此定義),它包含了
1)、類的名字(name)
2)、類(cls)
3)、category中所有給類添加的實例方法的列表(instanceMethods)
4)、category中所有添加的類方法的列表(classMethods)
5)、category實現(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的可為(可以添加實例方法,類方法,甚至可以實現(xiàn)協(xié)議,添加屬性)和不可為(無法添加實例變量)。
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值得吐槽的一點),我們忽略掉所有和我們無關(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)、首先
編譯器生成了實例方法列表OBJC$_CATEGORY_INSTANCE_METHODSMyClass$_MyAddition和屬性列表OBJC$_PROP_LISTMyClass$_MyAddition,兩者的命名都遵循了公共前綴+類名+category名字的命名方式,而且實例方法列表里面填充的正是我們在MyAddition這個category里面寫的方法printName,而屬性列表里面填充的也正是我們在MyAddition里添加的name屬性。還有一個需要注意到的事實就是category的名字用來給各種列表以及后面的category結(jié)構(gòu)體本身命名,而且有static來修飾,所以在同一個編譯單元里我們的category名不能重復,否則會出現(xiàn)編譯錯誤。
2)、其次,編譯器生成了category本身OBJC$_CATEGORYMyClass$_MyAddition,并用前面生成的列表來初始化category本身。
3)、最后,編譯器在DATA段下的objc_catlist section里保存了一個大小為1的category_t的數(shù)組L_OBJC_LABELCATEGORY$(當然,如果有多個category,會生成對應長度的數(shù)組^_^),用于運行期category的加載。
到這里,編譯器的工作就接近尾聲了,對于category在
運行期怎么加載,我們下節(jié)揭曉。


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

我們知道,Objective-C的運行是依賴OC的runtime的,而OC的runtime和其他系統(tǒng)庫一樣,是OS X和iOS通過dyld動態(tài)加載的。對于OC運行時,入口方法如下(在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的標準下,_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é)中講到的編譯器為我們準備的category_t數(shù)組,關(guān)于是如何加載catlist本身的,我們暫且不表,這和category本身的關(guān)系也不大,有興趣的同學可以去研究以下Apple的二進制格式和load機制。
略去PrintConnecting這個用于log的東西,這段代碼很容易理解:
1)、把category的實例方法、協(xié)議以及屬性添加到類上
2)、把category的類方法和協(xié)議添加到類的metaclass上

值得注意的是,在代碼中有一小段注釋 /?|| cat->classProperties?/,看來蘋果有過給類添加屬性的計劃啊。
ok,我們接著往里看,category的各種列表是怎么最終添加到類上的,就拿實例方法列表來說吧:
在上述的代碼片段里,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);} }

而對于添加類的實例方法而言,又會去調(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的實例方法列表拼成了一個大的實例方法列表,然后轉(zhuǎn)交給了attachMethodLists方法(我發(fā)誓,這是本節(jié)我們看的最后一段代碼了^_^),這個方法有點長,我們只看一小段:

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];}

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



3.3:旁枝末葉-category和+load方法

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

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

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

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)用,因為附加category到類的工作會先于+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里的對應方法。
這一節(jié)我們只是用很直觀的方式得到了問題的答案,有興趣的同學可以繼續(xù)去研究一下OC的運行時代碼。?


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

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


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

如上所見,我們知道在category里面是無法為category添加實例變量的。但是我們很多時候需要在category中添加和對象關(guān)聯(lián)的值,這個時候可以求助關(guān)聯(lián)對象來實現(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)對象的。這相當于把所有對象的關(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)對象的清理工作。




這個是從大牛的網(wǎng)址里看的資料,順便整理下來,連接地址:

http://tech.meituan.com/DiveIntoCategory.html(這里是內(nèi)部原理講解,很透徹)

http://www.jianshu.com/p/2bf61807b6b3


感謝大神:都是大神的精華,我整理成自己需要學習的效果以便以后自己快速查閱。





總結(jié)

以上是生活随笔為你收集整理的category-内部原理、运用场景、特点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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