前言
對(duì)于干活而言,針對(duì)Category的運(yùn)用,只要知道怎么用,有些需要注意的地方能夠注意到(比如,Category里定義的方法與主類相同時(shí),這個(gè)方法調(diào)用時(shí)實(shí)際上是Category里的)就可以了。另外,對(duì)于一些地方的運(yùn)用,可以知道如何給Category加屬性基本上也就夠了。
但實(shí)際上,有的時(shí)候,還是會(huì)碰到有人問(wèn)你一句Category是怎么實(shí)現(xiàn)的。從我個(gè)人的理解,其實(shí)就是希望你從其實(shí)現(xiàn)原理上來(lái)回答那幾個(gè)需要注意的地方,也就是當(dāng)Category中定義了一個(gè)與主類相同的方法時(shí),會(huì)調(diào)用Category的,而不是主類的。
當(dāng)然了,也可能會(huì)碰到再有人問(wèn)你如果就要調(diào)用主類的呢?
總之,林林總總就是這樣的。你能做多少事,跟你能說(shuō)多少事,這之間的差距就是你資(zhuang)深(bi)的程度了。當(dāng)然了,如果能從原理的角度上,加深對(duì)于Category的認(rèn)識(shí)也是很好的事情,所以,讓我們開(kāi)始資(zhuang)深(bi)吧~
Category的實(shí)現(xiàn)
先讓我們來(lái)看看Category的數(shù)據(jù)結(jié)構(gòu)
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;
上面這個(gè)就是Category的結(jié)構(gòu)體,我們可以看到,Category從結(jié)構(gòu)上來(lái)講,可以存儲(chǔ)實(shí)例方法(instanceMethods)、類方法(classMethods)、委托(protocols)以及屬性(instanceProperties).
但在這里我們要看到,結(jié)構(gòu)體中雖然有屬性,但并沒(méi)有實(shí)例變量(ivar)的存儲(chǔ),這就回答了我們一個(gè)問(wèn)題——為什么Category加屬性需要自己使用objc_getAssociatedObject的方式來(lái)實(shí)現(xiàn),實(shí)際上就是因?yàn)閏ategory里不能存儲(chǔ)實(shí)例變量。
比如我們可以在Category中寫(xiě)一個(gè)屬性,具體如下:
@interface NSObject (IndieBandName)
@property (nonatomic, copy) NSString *indieBandName;
@end
通常來(lái)講,我們這么寫(xiě)是不會(huì)有問(wèn)題的,編譯也過(guò)得去。但只要你一使用,就會(huì)報(bào)錯(cuò):錯(cuò)誤的內(nèi)容大概是告訴你找不到setIndieBandName方法這類的。所以,我們還要實(shí)現(xiàn)它的getter,setter方法
- (void)setIndieBandName:(NSString *)indieBandName
{
_indieBandName = [indieBandName copy];
}
寫(xiě)到這里發(fā)現(xiàn)問(wèn)題了吧,_indieBandName這個(gè)實(shí)例變量在Category中根本就沒(méi)生成!結(jié)合category的結(jié)構(gòu)體也可以理解,因?yàn)閏ategory_t里,也沒(méi)地方保存!所以,我們才使用objc_getAssociatedObject來(lái)保存對(duì)象,用來(lái)充當(dāng)getter/setter方法中負(fù)責(zé)返回和保存的實(shí)例變量。
好了讓我們繼續(xù)下去,我們知道了Category的結(jié)構(gòu)體后,就要看看Category里定義的方法是怎么加載的了。
看過(guò)OC對(duì)象內(nèi)存布局的人都知道,OC的類對(duì)象和元類對(duì)象中有methodList來(lái)分別保存實(shí)例方法和類方法。那么Category的方法到底是怎么保存在類對(duì)象里的呢?這就要從Category的加載聊起。
Category的加載
我們知道,Objective-C的運(yùn)行是依賴OC的runtime的,而OC的runtime和其他系統(tǒng)庫(kù)一樣,是OS X和iOS通過(guò)dyld動(dòng)態(tài)加載的。具體的入口函數(shù)大概是這個(gè)樣子:
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);
}
寫(xiě)這些東西就是為了說(shuō)明category被附加到類上面是在map_images的時(shí)候發(fā)生的,我們截取在_read_images方法的結(jié)尾,它大概是這個(gè)樣子的:
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);
}
}
}
}
從這個(gè)代碼中,我們可以看到,首先,系統(tǒng)獲取了Category的列表(catlist),之后就開(kāi)始遍歷,遍歷時(shí)拿到每一個(gè)Category(category_t *cat = catlist[i]),同時(shí)獲取Category所附著的類(class_t *cls = remapClass(cat->cls))。然后就開(kāi)始干活了,具體步驟如下:
- 如果cat結(jié)構(gòu)體中,instanceMethods,protocols,instanceProperties三個(gè)之中,只要有值,就會(huì)通過(guò)addUnattachedCategoryForClass(cat,cls,hi)方法,把Category和類先關(guān)聯(lián)起來(lái),但這時(shí)還沒(méi)有針對(duì)Category的方法做操作。
- 如果cat結(jié)構(gòu)體中,classMethods,protocols兩個(gè)當(dāng)中,只要有值,就睡通過(guò)addUnattachedCategoryForClass(cat,cls->isa,hi)方法,將Category和元類對(duì)象關(guān)聯(lián)起來(lái)。
PS. cls->isa指向的就是元類對(duì)象,這塊大家應(yīng)該知道哈~ 另外,我們發(fā)現(xiàn)上面與元類對(duì)象關(guān)聯(lián)的代碼中有一小段注釋掉的cat->classProperties。仔細(xì)想想,哎呦我靠,看來(lái)當(dāng)初蘋(píng)果還想弄個(gè)類屬性出來(lái)哈~
至此,我們已經(jīng)將Category有關(guān)實(shí)例方法、委托以及實(shí)例屬性關(guān)聯(lián)到類對(duì)象上,而類方法等關(guān)聯(lián)到元類對(duì)象上,后面就是要重新構(gòu)建類對(duì)象和元類對(duì)象的methodList了。
實(shí)際上,真正處理Category中方法的實(shí)現(xiàn),是一個(gè)叫做remethodizeClass的靜態(tài)方法,它大概是長(zhǎng)這個(gè)樣子:
static void remethodizeClass(class_t *cls)
{
category_list *cats;
BOOL isMeta;
rwlock_assert_writing(&runtimeLock);
isMeta = isMetaClass(cls);
// Re-methodizing: check for more categories
if ((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, protocols
BOOL 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 vtables
flushCaches(cls);
if (vtableAffected) flushVtables(cls);
}
}
這段代碼中,我們看到聲明了新的屬性列表(newproperties)和委托列表(newprotos),之后,又調(diào)用了attachCategoryMethods方法,實(shí)際上,這個(gè)方法就是將指定的類對(duì)象中的methodList與Category中methodList進(jìn)行整合的地方。
不管怎么樣,attach后,newproperties和newprotos都獲得了新的數(shù)據(jù),并把這些數(shù)據(jù)賦值給了cls。整體的融合也就完成了。
好了,看來(lái)attachCategoryMethods方法是其中的核心,讓我們來(lái)看看它都干了啥
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 first
int 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);
}
這段代碼主要的目的就是把所有的Category都拿出來(lái)遍歷一次,然后用新的方法列表mlists來(lái)填裝,填裝完成后,就把它連同類對(duì)象扔給了attachMethodLists方法了。
好吧,我們需要看一下attachMethodLists又都干了啥...... GFY
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 array
newLists[newCount++] = mlist;
.
.
.
// Copy old methods to the method list array
for (i = 0; i < oldCount; i++) {
newLists[newCount++] = oldLists[i];
}
整體來(lái)說(shuō),就是又有了一個(gè)新的數(shù)組,這數(shù)組首先是把所有的Category的方法都保存了下來(lái),之后,又把所謂的老方法列表追加到了數(shù)組中,這里的oldList實(shí)際上就是你類對(duì)象中原有的方法列表。換句話說(shuō),在重組的新方法列表中,Category方法都是排在前面的,而來(lái)方法都追加到了后面,這時(shí),如果發(fā)生Category和主類中都有相同的方法,那么Category的方法在前面而主類的方法在后面。
到這里,我們又能明確一件事情了,那就是為什么當(dāng)Category和主類擁有相同方法時(shí),實(shí)際被執(zhí)行的是Category的方法。因?yàn)樗谧钋懊媛铮?/strong> 同時(shí),我們也能夠發(fā)現(xiàn),主類的方法并沒(méi)有被覆蓋,而只是排在了后面。因此,如果我們想的話,只需要獲取當(dāng)前對(duì)象的方法列表,倒序找到第一個(gè)或者正向找到最后一個(gè)同名方法,那就是主類的方法了。
多個(gè)Category重名方法調(diào)用
緊接著問(wèn)題又來(lái)了,如果一個(gè)類上有多個(gè)Category,且都有相同的重名方法呢?
首先,根據(jù)上面的分析,肯定還是不會(huì)有主類方法什么事兒了。另外,也不可能兩個(gè)Category里的重名方法都被執(zhí)行,剩下的就是Category1和Category2兩個(gè)里面誰(shuí)會(huì)被執(zhí)行了。
如果做實(shí)驗(yàn)?zāi)銜?huì)發(fā)現(xiàn),其順序與CompileSources里的文件順序直接相關(guān),假設(shè)兩個(gè)Category分別為C1和C2。那么在CompileSources里的順序也是C1在前C2在后,其最終被執(zhí)行的實(shí)際上是C2中的方法,如果反過(guò)來(lái),C2在前,C1在后,那么執(zhí)行的就是C1了。
現(xiàn)在我們知道了,其執(zhí)行順序是文件加載的倒序順序哈。但這是否有根據(jù)呢?實(shí)際上,我們前面有一段代碼,如果仔細(xì)看看,就會(huì)發(fā)現(xiàn)端倪。代碼段如下:
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 first
int 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);
}
請(qǐng)注意,這段代碼中間while循環(huán)是倒序的,而不是從i=0開(kāi)始的。實(shí)際的情況我們就可以假設(shè)一下。實(shí)際在編譯時(shí),肯定是按照CompileSources的順序讀取文件的。因此attachCategoryMethods中的cats數(shù)組內(nèi),其順序也是C1在前C2在后(假定這就是CompileSources的順序),但由于i是降序開(kāi)始的,因此,首先被加載到mlists方法列表里的實(shí)際上就是C2了。所以才會(huì)有實(shí)驗(yàn)中的結(jié)果,即執(zhí)行的方法是多個(gè)Category在CompileSources中排列最后的那個(gè)文件。
+load方法
現(xiàn)在,我們知道了Category中的方法發(fā)生重名時(shí),并不是覆蓋關(guān)系,且Category的方法先于主類的方法被執(zhí)行。那么+load方法呢?如果主類和Category中都寫(xiě)了+load方法會(huì)怎樣?
通過(guò)模擬這種情況,我們就會(huì)發(fā)現(xiàn)實(shí)際上的順序。這里就直接說(shuō)結(jié)論了:先執(zhí)行主類的+load方法,之后再執(zhí)行category的+load方法。這兩個(gè)方法都可以被執(zhí)行到。另外,如果你在主類里用了category的方法也沒(méi)有問(wèn)題,因?yàn)閏ategory的加載是先于+load方法執(zhí)行之前就完成的。
調(diào)用主類方法
前面提到了,如果主類與Category有同名方法時(shí),被調(diào)用的是Category的方法,但如果我們就是想調(diào)用主類的方法呢?當(dāng)然是有辦法的,畢竟我們從前面的結(jié)論中得知,Category并不是覆蓋同名方法,只是排的比較靠前而已。因此,我們還是可以通過(guò)獲取方法列表,并找到最后一個(gè)同名方法就可以執(zhí)行了。(當(dāng)然,我想說(shuō),你TM別重名不是更好.....)
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);
}
AssociatedObject的存儲(chǔ)
前面已經(jīng)說(shuō)過(guò),由于Category中不能存有成員變量,因此,我們就需要使用AssociatedObject來(lái)存儲(chǔ)變量,用來(lái)充當(dāng)成員變量。但AssociatedObject里保存的變量到底在什么地方?我們后面就直接說(shuō)結(jié)論吧,就不粘源代碼了
AssociatedObject中的變量實(shí)際上是在一個(gè)全局的AssociationsHashMap中管理的,這相當(dāng)于把所有對(duì)象的關(guān)聯(lián)對(duì)象都存在一個(gè)全局map里面。而map的的key是這個(gè)對(duì)象的指針地址(任意兩個(gè)不同對(duì)象的指針地址一定是不同的),而這個(gè)map的value又是另外一個(gè)AssociationsHashMap,里面保存了關(guān)聯(lián)對(duì)象的kv對(duì)。
當(dāng)一個(gè)對(duì)象銷毀時(shí),系統(tǒng)會(huì)調(diào)用如下代碼:
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;
}
在這個(gè)方法中,可以看到assoc變量是標(biāo)識(shí),這個(gè)對(duì)象是否存在關(guān)聯(lián)對(duì)象,如果是的話,就會(huì)調(diào)用_object_remove_assocations(obj)方法,將指定的obj的關(guān)聯(lián)對(duì)象全部干掉。
總結(jié)
上面說(shuō)了那么多,實(shí)際上也就結(jié)合一些源碼,總結(jié)和加強(qiáng)記憶一下東西
- Categroy的實(shí)現(xiàn),運(yùn)行時(shí)先把Category中的方法遍歷出來(lái),形成一個(gè)新的方法數(shù)組,之后再將主類上原有的方法追加上去,從而變成Category方法在前,主類方法在后的一個(gè)新的methodList。
- 在主類和Category中,同名方法可以同時(shí)存在,且不不是覆蓋關(guān)系。運(yùn)行時(shí),當(dāng)調(diào)用到同名方法,被調(diào)用的是在方法列表中排在前面的Category方法。
- Category中,同名方法不是覆蓋關(guān)系,因此還是可以想辦法調(diào)用主類方法的。其途徑就是獲取當(dāng)前對(duì)象的方法列表,從列表中找出最后一個(gè)同名方法,就是主類的方法。
- 在主類的+load方法中可以調(diào)用Category的方法,因?yàn)镃ategory的加載是在load方法之前就完成的。對(duì)于主類和Category中都有+load的方法的時(shí)候,順序是先主類后Category。
- associatedObject保存變量是保存在一個(gè)全局的HashMap中,對(duì)象的地址是Key,value是另一個(gè)HashMap,這個(gè)HashMap里保存Key-Value對(duì)。