為什么Category無法添加實例變量?
Category是無法添加實例變量的,當一個類被編譯時,實例變量的布局也就形成了,如果Category在運行時添加實例變量就會破壞類的內存布局,這對編譯型語言來說是災難性的。
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里的方法會覆蓋掉類里同名的方法
在運行時,category的方法被添加到類的方法列表里,并且會被添加到類原有的方法的前面。運行時在查找方法的時候是順著方法列表的順序查找的,它只要一找到對應名字的方法就會停止查找。
Category是如何給類添加方法的?
在運行時會把Category里的方法添加到類里。
在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;
};
自定義一個類:
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
然后打開得到的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;
};
//生成實例方法列表
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,
};
- 編譯器會先生成實例方法列表
_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition和屬性列表_OBJC_$_PROP_LIST_MyClass_$_MyAddition __attribute__。而且實例方法列表里面填充的正是我們在MyAddition這個Category里面寫的方法printName,而屬性列表里面填充的也正是我們在MyAddition里添加的name屬性; - 之后,編譯器會生成Category本身
_OBJC_$_CATEGORY_MyClass_$_MyAddition,并且使用上面已經生成的實例方法列表和屬性列表來初始化; - 最后,編譯器在DATA段下的objc_catlist section里保存了一個大小為1的Category_t的數組
L_OBJC_LABELCATEGORY$(當然,如果有多個Category,會生成對應長度的數組),用于運行期Category的加載。
對于OC運行時,入口方法如下(在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被附加到類上面是在map_images的時候發(fā)生的,在new-ABI的標準下,_objc_init里面的調用的map_images最終會調用objc-runtime-new.mm里面的_read_images方法,而在_read_images方法的結尾,有以下的代碼片段:
// 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的實例方法、協(xié)議以及屬性添加到類上
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的類方法、協(xié)議以及類屬性添加到元類上
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é)中講到的編譯器為我們準備的category_t數組,之后做了兩件事:
- 把category的實例方法、協(xié)議以及屬性添加到類上;
- 把category的類方法、協(xié)議以及類屬性添加到元類上。
addUnattachedCategoryForClass只是把類和category做一個關聯(lián)映射,而remethodizeClass才是真正去處理添加事宜的函數:
/***********************************************************************
* 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);
}
}
而對于添加類的實例方法而言,又會去調用attachCategories這個方法,我們去看下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的實例方法列表放到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做的工作相對比較簡單,它只是把所有category的實例方法列表拼成了一個大的實例方法列表,然后轉交給了attachLists函數,attachLists函數在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的方法會被添加到類原有的方法的前面。如果category和原來類都有methodA,那么category附加完成之后,類的方法列表里會有兩個methodA這也就是我們平常所說的category的方法會“覆蓋”掉原來類的同名方法的原因。這是因為運行時在查找方法的時候是順著方法列表的順序查找的,它只要一找到對應名字的方法就會停止查找。
類的多個類別有相同方法名
如果類或類別實現(xiàn)了+load方法,當類或類別被加入到OC的runtime時,會調用類或類別實現(xiàn)的+load方法,并且類的load方法在類別的load方法之前調用。如果有多個類別實現(xiàn)了+load方法,則多個類別里的+load方法的調用順序是由compile sources里的文件順序決定的,在compile sources里后面的category文件會先調用+load方法。
類和類別里其他的同名方法在調用時,類別里的方法會取代類里的方法(原因之前有提到),多個類別里的同名方法會調用哪一個也是由compile sources里的category文件順序決定的。
如果類別里有和類同名的方法,會調用類別里的方法,如果一個類有多個類別且每個類別里都有同名的方法,那么調用那個方法是由build phase里的順序決定的。在build phase里后編譯的category,在運行時里category的方法會被添加到類的方法列表里前面的位置。
我們的代碼里有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):

此時的complie sources里的順序是這樣的:

運行項目,我們會看到控制臺打印很多東西出來,我們只找到我們想要的信息,順序如下:
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]
可以看出,類的printName方法會被Category2里的printName取代;+load方法的調用順序是先調用類里的load方法,然后類別里的load方法的調用順序和編譯順序是一致的。并且category的方法添加到類里的工作實現(xiàn)與load方法調用的,因此可以在load方法里調用
換一下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]
此時category1里的printName會最終取代類里的printName。
通過關聯(lián)對象的方法添加屬性
Category里可以添加屬性,但只會添加setter和getter方法的聲明,不會添加setter和getter方法的實現(xiàn)和實例變量,
我們可以通過 Associated Objects 來彌補不能添加實例變量這一不足。
相關函數:
/**
* 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 用于給對象添加關聯(lián)對象,傳入 nil 則可以移除已有的關聯(lián)對象;
- objc_getAssociatedObject 用于獲取關聯(lián)對象;
這兩個方法都要傳入一個key值,這個 key 值必須保證是一個對象級別(的唯一常量。一般來說,有以下三種推薦的 key 值:
- 聲明 static char kAssociatedObjectKey; ,使用 &kAssociatedObjectKey 作為 key 值;
- 聲明 static void *kAssociatedObjectKey = &kAssociatedObjectKey; ,使用 kAssociatedObjectKey 作為 key 值;
- 用selector ,使用 getter 方法的名稱作為 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,當對象的關聯(lián)對象釋放了,調用objc_getAssociatedObject()會崩潰。因為objc_setAssociatedObject ()存儲的是關聯(lián)對象的地址,雖然關聯(lián)對象釋放了,但是對象存儲的關聯(lián)對象的地址并沒有被移除,此時調用objc_getAssociatedObject()會崩潰。所以我們在使用弱引用的關聯(lián)對象時要非常小心。
關聯(lián)對象存在什么地方呢? 如何存儲? 對象銷毀時候如何處理關聯(lián)對象呢?
所有的關聯(lián)對象都是由一個類AssociationsManager管理的,AssociationsManager里面是有一個靜態(tài)的AssociationsHashMap來存儲所有的關聯(lián)對象的。AssociationsHashMap的key是對象的指針地址,value是ObjectAssociationMap,ObjectAssociationMap也是一個哈希表,里面存放了以key為指針地址的對象的所有的關聯(lián)對象的key-value。
一個對象的所有關聯(lián)對象是在這個對象被釋放時調用的 _object_remove_assocations 函數中被移除的。
http://blog.leichunfeng.com/blog/2015/06/26/objective-c-associated-objects-implementation-principle/