為什么Category無(wú)法添加實(shí)例變量肆良?
Category是無(wú)法添加實(shí)例變量的拨与,當(dāng)一個(gè)類(lèi)被編譯時(shí)忆蚀,實(shí)例變量的布局也就形成了根蟹,如果Category在運(yùn)行時(shí)添加實(shí)例變量就會(huì)破壞類(lèi)的內(nèi)存布局,這對(duì)編譯型語(yǔ)言來(lái)說(shuō)是災(zāi)難性的拷肌。
https://tech.meituan.com/DiveIntoCategory.html
http://yulingtianxia.com/blog/2014/11/05/objective-c-runtime/
https://stackoverflow.com/questions/39429512/objective-c-categories-doesnt-allow-to-add-instance-variables?noredirect=1&lq=1
https://stackoverflow.com/questions/39429512/objective-c-categories-doesnt-allow-to-add-instance-variables?noredirect=1&lq=1
為什么category里的方法會(huì)覆蓋掉類(lèi)里同名的方法
在運(yùn)行時(shí)到旦,category的方法被添加到類(lèi)的方法列表里,并且會(huì)被添加到類(lèi)原有的方法的前面巨缘。運(yùn)行時(shí)在查找方法的時(shí)候是順著方法列表的順序查找的添忘,它只要一找到對(duì)應(yīng)名字的方法就會(huì)停止查找。
Category是如何給類(lèi)添加方法的若锁?
在運(yùn)行時(shí)會(huì)把Category里的方法添加到類(lèi)里搁骑。
在runtime的源碼(我看的是objc4-723)objc-runtime-new.h里可以找到Category的定義:
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;
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties;
};
自定義一個(gè)類(lèi):
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到底會(huì)變成什么:
clang -rewrite-objc MyClass.m
然后打開(kāi)得到的MyClass.cpp文件,在文件最后可以找到下面的代碼:
struct _category_t {
const char *name;
struct _class_t *cls;
const struct _method_list_t *instance_methods;
const struct _method_list_t *class_methods;
const struct _protocol_list_t *protocols;
const struct _prop_list_t *properties;
};
//生成實(shí)例方法列表
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"}}
};
//生成category本身
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 struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= {
&_OBJC_$_CATEGORY_MyClass_$_MyAddition,
};
- 編譯器會(huì)先生成實(shí)例方法列表
_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition
和屬性列表_OBJC_$_PROP_LIST_MyClass_$_MyAddition __attribute__
。而且實(shí)例方法列表里面填充的正是我們?cè)贛yAddition這個(gè)Category里面寫(xiě)的方法printName拴清,而屬性列表里面填充的也正是我們?cè)贛yAddition里添加的name屬性靶病; - 之后,編譯器會(huì)生成Category本身
_OBJC_$_CATEGORY_MyClass_$_MyAddition
口予,并且使用上面已經(jīng)生成的實(shí)例方法列表和屬性列表來(lái)初始化娄周; - 最后,編譯器在DATA段下的objc_catlist section里保存了一個(gè)大小為1的Category_t的數(shù)組
L_OBJC_LABELCATEGORY$
(當(dāng)然沪停,如果有多個(gè)Category煤辨,會(huì)生成對(duì)應(yīng)長(zhǎng)度的數(shù)組)裳涛,用于運(yùn)行期Category的加載。
對(duì)于OC運(yùn)行時(shí)众辨,入口方法如下(在objc-os.mm文件中):
/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/
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();
static_init();
lock_init();
exception_init();
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
category被附加到類(lèi)上面是在map_images的時(shí)候發(fā)生的端三,在new-ABI的標(biāo)準(zhǔn)下,_objc_init里面的調(diào)用的map_images最終會(huì)調(diào)用objc-runtime-new.mm里面的_read_images方法鹃彻,而在_read_images方法的結(jié)尾郊闯,有以下的代碼片段:
// Discover categories.
for (EACH_HEADER) {
category_t **catlist =
_getObjc2CategoryList(hi, &count);
bool hasClassProperties = hi->info()->hasCategoryClassProperties();
for (i = 0; i < count; i++) {
category_t *cat = catlist[I];
Class cls = remapClass(cat->cls);
if (!cls) {
// Category's target class is missing (probably weak-linked).
// Disavow any knowledge of this category.
catlist[i] = nil;
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;
//把category的實(shí)例方法、協(xié)議以及屬性添加到類(lèi)上
if (cat->instanceMethods || cat->protocols
|| cat->instanceProperties)
{
addUnattachedCategoryForClass(cat, cls, hi);
if (cls->isRealized()) {
remethodizeClass(cls);
classExists = YES;
}
if (PrintConnecting) {
_objc_inform("CLASS: found category -%s(%s) %s",
cls->nameForLogging(), cat->name,
classExists ? "on existing class" : "");
}
}
//把category的類(lèi)方法蛛株、協(xié)議以及類(lèi)屬性添加到元類(lèi)上
if (cat->classMethods || cat->protocols
|| (hasClassProperties && cat->_classProperties))
{
addUnattachedCategoryForClass(cat, cls->ISA(), hi);
if (cls->ISA()->isRealized()) {
remethodizeClass(cls->ISA());
}
if (PrintConnecting) {
_objc_inform("CLASS: found category +%s(%s)",
cls->nameForLogging(), cat->name);
}
}
}
}
首先团赁,我們拿到的catlist就是上節(jié)中講到的編譯器為我們準(zhǔn)備的category_t數(shù)組,之后做了兩件事:
- 把category的實(shí)例方法谨履、協(xié)議以及屬性添加到類(lèi)上欢摄;
- 把category的類(lèi)方法、協(xié)議以及類(lèi)屬性添加到元類(lèi)上笋粟。
addUnattachedCategoryForClass
只是把類(lèi)和category做一個(gè)關(guān)聯(lián)映射怀挠,而remethodizeClass
才是真正去處理添加事宜的函數(shù):
/***********************************************************************
* remethodizeClass
* Attach outstanding categories to an existing class.
* Fixes up cls's method list, protocol list, and property list.
* Updates method caches for cls and its subclasses.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void remethodizeClass(Class cls)
{
category_list *cats;
bool isMeta;
runtimeLock.assertWriting();
isMeta = cls->isMetaClass();
// Re-methodizing: check for more categories
if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
if (PrintConnecting) {
_objc_inform("CLASS: attaching categories to class '%s' %s",
cls->nameForLogging(), isMeta ? "(meta)" : "");
}
attachCategories(cls, cats, true /*flush caches*/);
free(cats);
}
}
而對(duì)于添加類(lèi)的實(shí)例方法而言,又會(huì)去調(diào)用attachCategories
這個(gè)方法害捕,我們?nèi)タ聪?code>attachCategories:
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order,
// oldest categories first.
static void
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
if (!cats) return;
if (PrintReplacedMethods) printReplacements(cls, cats);
bool isMeta = cls->isMetaClass();
// fixme rearrange to remove these intermediate allocations
method_list_t **mlists = (method_list_t **)
malloc(cats->count * sizeof(*mlists));
property_list_t **proplists = (property_list_t **)
malloc(cats->count * sizeof(*proplists));
protocol_list_t **protolists = (protocol_list_t **)
malloc(cats->count * sizeof(*protolists));
// Count backwards through cats to get newest categories first
int mcount = 0;
int propcount = 0;
int protocount = 0;
int i = cats->count;
bool fromBundle = NO;
while (i--) {
auto& entry = cats->list[I];
//將所有的category的實(shí)例方法列表放到mlists列表中
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
mlists[mcount++] = mlist;
fromBundle |= entry.hi->isBundle();
}
//將所有的category的屬性列表放到proplists列表中
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
proplists[propcount++] = proplist;
}
//將所有的category的協(xié)議列表放到protolists列表中
protocol_list_t *protolist = entry.cat->protocols;
if (protolist) {
protolists[protocount++] = protolist;
}
}
auto rw = cls->data();
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
rw->methods.attachLists(mlists, mcount);
free(mlists);
if (flush_caches && mcount > 0) flushCaches(cls);
rw->properties.attachLists(proplists, propcount);
free(proplists);
rw->protocols.attachLists(protolists, protocount);
free(protolists);
}
attachCategories
做的工作相對(duì)比較簡(jiǎn)單绿淋,它只是把所有category的實(shí)例方法列表拼成了一個(gè)大的實(shí)例方法列表,然后轉(zhuǎn)交給了attachLists
函數(shù)吨艇,attachLists
函數(shù)在objc-runtime-new.h中:
void attachLists(List* const * addedLists, uint32_t addedCount) {
if (addedCount == 0) return;
if (hasArray()) {
// many lists -> many lists
uint32_t oldCount = array()->count;
uint32_t newCount = oldCount + addedCount;
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
array()->count = newCount;
memmove(array()->lists + addedCount, array()->lists,
oldCount * sizeof(array()->lists[0]));
memcpy(array()->lists, addedLists,
addedCount * sizeof(array()->lists[0]));
}
else if (!list && addedCount == 1) {
// 0 lists -> 1 list
list = addedLists[0];
}
else {
// 1 list -> many lists
List* oldList = list;
uint32_t oldCount = oldList ? 1 : 0;
uint32_t newCount = oldCount + addedCount;
setArray((array_t *)malloc(array_t::byteSize(newCount)));
array()->count = newCount;
if (oldList) array()->lists[addedCount] = oldList;
memcpy(array()->lists, addedLists,
addedCount * sizeof(array()->lists[0]));
}
}
從上面的memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0])); }
可以看出躬它,category的方法會(huì)被添加到類(lèi)原有的方法的前面。如果category和原來(lái)類(lèi)都有methodA东涡,那么category附加完成之后,類(lèi)的方法列表里會(huì)有兩個(gè)methodA這也就是我們平常所說(shuō)的category的方法會(huì)“覆蓋”掉原來(lái)類(lèi)的同名方法的原因倘待。這是因?yàn)檫\(yùn)行時(shí)在查找方法的時(shí)候是順著方法列表的順序查找的疮跑,它只要一找到對(duì)應(yīng)名字的方法就會(huì)停止查找。
類(lèi)的多個(gè)類(lèi)別有相同方法名
如果類(lèi)或類(lèi)別實(shí)現(xiàn)了+load方法凸舵,當(dāng)類(lèi)或類(lèi)別被加入到OC的runtime時(shí)祖娘,會(huì)調(diào)用類(lèi)或類(lèi)別實(shí)現(xiàn)的+load方法,并且類(lèi)的load方法在類(lèi)別的load方法之前調(diào)用啊奄。如果有多個(gè)類(lèi)別實(shí)現(xiàn)了+load方法渐苏,則多個(gè)類(lèi)別里的+load方法的調(diào)用順序是由compile sources里的文件順序決定的,在compile sources里后面的category文件會(huì)先調(diào)用+load方法菇夸。
類(lèi)和類(lèi)別里其他的同名方法在調(diào)用時(shí)琼富,類(lèi)別里的方法會(huì)取代類(lèi)里的方法(原因之前有提到),多個(gè)類(lèi)別里的同名方法會(huì)調(diào)用哪一個(gè)也是由compile sources里的category文件順序決定的庄新。
如果類(lèi)別里有和類(lèi)同名的方法鞠眉,會(huì)調(diào)用類(lèi)別里的方法薯鼠,如果一個(gè)類(lèi)有多個(gè)類(lèi)別且每個(gè)類(lèi)別里都有同名的方法,那么調(diào)用那個(gè)方法是由build phase里的順序決定的械蹋。在build phase里后編譯的category出皇,在運(yùn)行時(shí)里category的方法會(huì)被添加到類(lèi)的方法列表里前面的位置。
我們的代碼里有MyClass和MyClass的兩個(gè)category (Category1和Category2)哗戈,MyClass和兩個(gè)category都添加了+load方法郊艘,并且Category1和Category2都寫(xiě)了MyClass的printName方法:
在Xcode中點(diǎn)擊Edit Scheme,添加如下兩個(gè)環(huán)境變量(可以在執(zhí)行l(wèi)oad方法以及加載category的時(shí)候打印log信息唯咬,更多的環(huán)境變量選項(xiàng)可參見(jiàn)objc-private.h):
此時(shí)的complie sources里的順序是這樣的:
運(yùn)行項(xiàng)目暇仲,我們會(huì)看到控制臺(tái)打印很多東西出來(lái),我們只找到我們想要的信息副渴,順序如下:
objc[63746]: REPLACED: -[MyClass printName] by category Category1
objc[63746]: REPLACED: -[MyClass printName] by category Category2
···
···
···
objc[64365]: LOAD: class 'MyClass' scheduled for +load
objc[64365]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[64365]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[63746]: LOAD: +[MyClass load]
objc[63746]: LOAD: +[MyClass(Category1) load]
objc[63746]: LOAD: +[MyClass(Category2) load]
可以看出奈附,類(lèi)的printName方法會(huì)被Category2里的printName取代;+load方法的調(diào)用順序是先調(diào)用類(lèi)里的load方法煮剧,然后類(lèi)別里的load方法的調(diào)用順序和編譯順序是一致的斥滤。并且category的方法添加到類(lèi)里的工作實(shí)現(xiàn)與load方法調(diào)用的,因此可以在load方法里調(diào)用
換一下complie sources里的順序:
objc[63746]: REPLACED: -[MyClass printName] by category Category2
objc[63746]: REPLACED: -[MyClass printName] by category Category1
···
···
···
objc[64433]: LOAD: class 'MyClass' scheduled for +load
objc[64433]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[64433]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[64433]: LOAD: +[MyClass load]
objc[64433]: LOAD: +[MyClass(Category2) load]
objc[64433]: LOAD: +[MyClass(Category1) load]
此時(shí)category1里的printName會(huì)最終取代類(lèi)里的printName勉盅。
通過(guò)關(guān)聯(lián)對(duì)象的方法添加屬性
Category里可以添加屬性佑颇,但只會(huì)添加setter和getter方法的聲明,不會(huì)添加setter和getter方法的實(shí)現(xiàn)和實(shí)例變量草娜,
我們可以通過(guò) Associated Objects 來(lái)彌補(bǔ)不能添加實(shí)例變量這一不足挑胸。
相關(guān)函數(shù):
/**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.
* @param key The key for the association.
* @param value The value to associate with the key key for object. Pass nil to clear an existing association.
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
*
*/
OBJC_EXPORT void
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
id _Nullable value, objc_AssociationPolicy policy)
/**
* Returns the value associated with a given object for a given key.
*
* @param object The source object for the association.
* @param key The key for the association.
*
* @return The value associated with the key \e key for \e object.
*/
OBJC_EXPORT id _Nullable
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
- objc_setAssociatedObject 用于給對(duì)象添加關(guān)聯(lián)對(duì)象,傳入 nil 則可以移除已有的關(guān)聯(lián)對(duì)象宰闰;
- objc_getAssociatedObject 用于獲取關(guān)聯(lián)對(duì)象茬贵;
這兩個(gè)方法都要傳入一個(gè)key值,這個(gè) key 值必須保證是一個(gè)對(duì)象級(jí)別(的唯一常量移袍。一般來(lái)說(shuō)解藻,有以下三種推薦的 key 值:
- 聲明 static char kAssociatedObjectKey; ,使用 &kAssociatedObjectKey 作為 key 值;
- 聲明 static void *kAssociatedObjectKey = &kAssociatedObjectKey; 葡盗,使用 kAssociatedObjectKey 作為 key 值螟左;
- 用selector ,使用 getter 方法的名稱(chēng)作為 key 值觅够。
@interface MyClass (Category1)
@property (nonatomic, copy) NSString *name;
@end
#import "MyClass+Category1.h"
#import <objc/runtime.h>
@implementation MyClass (Category1)
- (void)setName:(NSString *)name{
objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY);
}
- (NSString *)name{
return objc_getAssociatedObject(self, _cmd);
}
@end
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
* The association is not made atomically. */
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.
* The association is not made atomically. */
OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.
* The association is made atomically. */
OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied.
* The association is made atomically. */
};
如果使用OBJC_ASSOCIATION_ASSIGN
,當(dāng)對(duì)象的關(guān)聯(lián)對(duì)象釋放了胶背,調(diào)用objc_getAssociatedObject()
會(huì)崩潰。因?yàn)?code>objc_setAssociatedObject ()存儲(chǔ)的是關(guān)聯(lián)對(duì)象的地址喘先,雖然關(guān)聯(lián)對(duì)象釋放了钳吟,但是對(duì)象存儲(chǔ)的關(guān)聯(lián)對(duì)象的地址并沒(méi)有被移除,此時(shí)調(diào)用objc_getAssociatedObject()
會(huì)崩潰苹祟。所以我們?cè)谑褂萌跻玫年P(guān)聯(lián)對(duì)象時(shí)要非常小心砸抛。
關(guān)聯(lián)對(duì)象存在什么地方呢评雌? 如何存儲(chǔ)? 對(duì)象銷(xiāo)毀時(shí)候如何處理關(guān)聯(lián)對(duì)象呢直焙?
所有的關(guān)聯(lián)對(duì)象都是由一個(gè)類(lèi)AssociationsManager
管理的景东,AssociationsManager
里面是有一個(gè)靜態(tài)的AssociationsHashMap
來(lái)存儲(chǔ)所有的關(guān)聯(lián)對(duì)象的。AssociationsHashMap
的key是對(duì)象的指針地址奔誓,value是ObjectAssociationMap
斤吐,ObjectAssociationMap
也是一個(gè)哈希表,里面存放了以key為指針地址的對(duì)象的所有的關(guān)聯(lián)對(duì)象的key-value厨喂。
一個(gè)對(duì)象的所有關(guān)聯(lián)對(duì)象是在這個(gè)對(duì)象被釋放時(shí)調(diào)用的 _object_remove_assocations 函數(shù)中被移除的和措。
http://blog.leichunfeng.com/blog/2015/06/26/objective-c-associated-objects-implementation-principle/