分類優(yōu)點
- 聲明私有方法
- 分解體積龐大的類文件
- 把Framework私有方法公開
- 模擬多繼承(另外可以模擬多繼承的還有protocol)
Category(objc_category)
/// An opaque type that represents a category.
typedef struct objc_category *Category;
struct objc_category {
// 分類名
char * _Nonnull category_name OBJC2_UNAVAILABLE;
// 分類所屬的類名
char * _Nonnull class_name OBJC2_UNAVAILABLE;
// 實例方法列表
struct objc_method_list * _Nullable instance_methods OBJC2_UNAVAILABLE;
// 類方法列表
struct objc_method_list * _Nullable class_methods OBJC2_UNAVAILABLE;
// 分類所實現的協議列表
struct objc_protocol_list * _Nullable protocols OBJC2_UNAVAILABLE;
}
分類特點
- 分類是用于給原有類添加方法的,因為分類的結構體指針中蜀漆,沒有屬性列表,只有方法列表竣付。原則上講它只能添加方法, 不能添加屬性(成員變量),實際上可以通過其它方式添加屬性;
- 分類中的可以寫@property, 但不會生成setter/getter方法, 也不會生成實現以及私有的成員變量,會編譯通過巫财,但是引用變量會報錯;
- 如果分類中有和原有類同名的方法, 會優(yōu)先調用分類中的方法, 就是說會忽略原有類的方法贯溅,同名方法調用的優(yōu)先級為 分類 > 本類 > 父類;
- 如果多個分類中都有和原有類中同名的方法, 那么調用該方法的時候執(zhí)行誰由編譯器決定啄育;編譯器會執(zhí)行最后一個參與編譯的分類中的方法。
- 運行時決議
- 同名分類方法生效取決于編譯順序
- 名字相同的分類會引起編譯報錯
Persion.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)printName;
@end
@interface Person(Test)
@property(nonatomic, copy) NSString *name;
- (void)printName;
@end
Persion.m
#import "Person.h"
@implementation Person
- (void)printName
{
NSLog(@"%@", @"Person");
}
@end
@implementation Person(Test)
- (void)printName
{
NSLog(@"%@", @"Person Test");
}
@end
輸入命令:clang -rewrite-objc Person+A.m
得到:Person+A.cpp
在文件的最后有如下代碼:
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_Person_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_objc_method),
1,
{{(struct objc_selector *)"printName", "v16@0:8", (void *)_I_Person_Test_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_Person_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_prop_t),
1,
{{"name","T@\"NSString\",C,N"}}
};
extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_Person;
static struct _category_t _OBJC_$_CATEGORY_Person_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"Person",
0, // &OBJC_CLASS_$_Person,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_Test,
0,
0,
(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_Person_$_Test,
};
static void OBJC_CATEGORY_SETUP_$_Person_$_Test(void ) {
_OBJC_$_CATEGORY_Person_$_Test.cls = &OBJC_CLASS_$_Person;
}
#pragma section(".objc_inithooks$B", long, read, write)
__declspec(allocate(".objc_inithooks$B")) static void *OBJC_CATEGORY_SETUP[] = {
(void *)&OBJC_CATEGORY_SETUP_$_Person_$_Test,
};
static struct _class_t *L_OBJC_LABEL_CLASS_$ [1] __attribute__((used, section ("__DATA, __objc_classlist,regular,no_dead_strip")))= {
&OBJC_CLASS_$_Person,
};
static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= {
&_OBJC_$_CATEGORY_Person_$_Test,
};
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };
我們可以看到拌消,
1)挑豌、首先編譯器生成了實例方法列表_OBJC__CATEGORY_INSTANCE_METHODS_Person__Test和屬性列表_OBJC__PROP_LIST_Person__Test,兩者的命名都遵循了公共前綴+類名+category名字的命名方式墩崩,而且實例方法列表里面填充的正是我們在Person這個category里面寫的方法printName氓英,而屬性列表里面填充的也正是我們在Person里添加的name屬性。還有一個需要注意到的事實就是category的名字用來給各種列表以及后面的category結構體本身命名鹦筹,而且有static來修飾铝阐,所以在同一個編譯單元里我們的category名不能重復,否則會出現編譯錯誤铐拐。
2)徘键、其次,編譯器生成了category本身_OBJC__CATEGORY_Person__Test遍蟋,并用前面生成的列表來初始化category本身吹害。
3)、最后虚青,編譯器在DATA段下的_objc_catlist section里保存了一個大小為1的category_t的數組L_OBJC_LABEL_CATEGORY(當然它呀,如果有多個category,會生成對應長度的數組)棒厘,用于運行期category的加載纵穿。
到這里,編譯器的工作就接近尾聲了奢人。
Category加載調用棧
我們知道谓媒,Objective-C的運行是依賴OC的runtime的,而OC的runtime和其他系統(tǒng)庫一樣达传,是OS X和iOS通過dyld動態(tài)加載的篙耗。
想了解更多dyld地同學可以移步這里(3)。
對于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里面的調用的map_images最終會調用objc-runtime-new.mm里面的_read_images方法搂妻,而在_read_images方法的結尾蒙保,有以下的代碼片段:
// 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數組欲主,關于是如何加載catlist本身的邓厕,我們暫且不表,這和category本身的關系也不大扁瓢,有興趣的同學可以去研究以下Apple的二進制格式和load機制详恼。
略去PrintConnecting這個用于log的東西,這段代碼很容易理解:
1)引几、把category的實例方法昧互、協議以及屬性添加到類上
2)、把category的類方法和協議添加到類的metaclass上
值得注意的是伟桅,在代碼中有一小段注釋 /* || cat->classProperties */敞掘,看來蘋果有過給類添加屬性的計劃啊。
我們接著往里看楣铁,category的各種列表是怎么最終添加到類上的玖雁,就拿實例方法列表來說吧:
在上述的代碼片段里,addUnattachedCategoryForClass只是把類和category做一個關聯映射盖腕,而remethodizeClass才是真正去處理添加事宜的功臣赫冬。
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);
}
}
而對于添加類的實例方法而言,又會去調用attachCategoryMethods這個方法赊堪,我們去看下attachCategoryMethods:
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);
}
attachCategoryMethods做的工作相對比較簡單面殖,它只是把所有category的實例方法列表拼成了一個大的實例方法列表,然后轉交給了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 array
newLists[newCount++] = mlist;
.
.
.
// Copy old methods to the method list array
for (i = 0; i < oldCount; i++) {
newLists[newCount++] = oldLists[i];
}
需要注意的有兩點:
1)遵绰、category的方法沒有“完全替換掉”原來類已經有的方法辽幌,也就是說如果category和原來類都有methodA,那么category附加完成之后椿访,類的方法列表里會有兩個methodA
2)乌企、category的方法被放到了新方法列表的前面,而原來類的方法被放到了新方法列表的后面成玫,這也就是我們平常所說的category的方法會“覆蓋”掉原來類的同名方法加酵,這是因為運行時在查找方法的時候是順著方法列表的順序查找的拳喻,它只要一找到對應名字的方法,就會罷休_猪腕,殊不知后面可能還有一樣名字的方法冗澈。
方法覆蓋
怎么調用到原來類中被category覆蓋掉的方法? 對于這個問題陋葡,我們已經知道category其實并不是完全替換掉原來類的同名方法亚亲,只是category在方法列表的前面而已,所以我們只要順著方法列表找到最后一個對應名字的方法腐缤,就可以調用原來類的方法:
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);
}
關聯對象
Person+Category1.m
#import "Person+Category1.h"
#import <objc/runtime.h>
@implementation Person (Category1)
+ (void)load {
NSLog(@"Person Category1 load");
}
- (void)printName
{
NSLog(@"%@", @"Person Category1 printName");
}
- (void)setName:(NSString *)name
{
objc_setAssociatedObject(self,
"name",
name,
OBJC_ASSOCIATION_COPY);
}
- (NSString*)name
{
NSString *nameObject = objc_getAssociatedObject(self, "name");
return nameObject;
}
@end
但是關聯對象又是存在什么地方呢捌归? 如何存儲? 對象銷毀時候如何處理關聯對象呢岭粤?
我們去翻一下runtime的源碼惜索,在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 exists
ObjectAssociationMap *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);
}
我們可以看到所有的關聯對象都由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來存儲所有的關聯對象的剃浇。這相當于把所有對象的關聯對象都存在一個全局map里面门扇。而map的的key是這個對象的指針地址(任意兩個不同對象的指針地址一定是不同的),而這個map的value又是另外一個AssociationsHashMap偿渡,里面保存了關聯對象的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的銷毀對象函數objc_destructInstance里面會判斷這個對象有沒有關聯對象吉拳,如果有,會調用_object_remove_assocations做關聯對象的清理工作适揉。
Category和Extension比較
Extension看起來很像一個匿名的Category留攒,但是Extension和有名字的Category幾乎完全是兩個東西,Extension編譯期決議嫉嘀,它就是類的一部分炼邀,在編譯期和頭文件里的@interface以及和實現文件里的@implement一起形成一個完整的類,它隨著類的產生而產生剪侮,亦隨之一起消亡拭宁,Extension一般用來隱藏類的私有信息,你必須有一個類的源碼才能為一個類添加Extension瓣俯,所以你無法為系統(tǒng)的類添加Extension(詳見2)
但是Category實在運行期決議的杰标。
就category和extension的區(qū)別來看,我們可以推導出一個明顯的事實彩匕,extension可以添加實例變量腔剂,而category是無法添加實例變量的(因為在運行期,對象的內存布局已經確定驼仪,如果添加實例變量就會破壞類的內部布局掸犬,這對編譯型語言來說是災難性的)袜漩。
+initialize和+load
+initialize是通過objc_msgSend進行調用的
如果子類沒有實現+initialize,會調用父類的+initialize(所以父類的+initialize可能會被調用多次)
如果分類實現了+initialize湾碎,就覆蓋類本身的+initialize調用
+load是通過函數指針指向函數噪服,拿到函數地址,分開來直接調用的胜茧,直接通過內存地址查找調用的。
load是runtime加載類纵菌、分類的時候調用(只會調用1次)
initialize是類第一次接收到消息的時候調用学赛,每一個類只會initialize一次
參考:
https://tech.meituan.com/2015/03/03/diveintocategory.html
Demo地址:Category