簡介
當(dāng)我們功能越來越多時公浪,單一文件的體積就會變大他宛,甚至臃腫。而多人配合開發(fā)一個文件時因悲,還會出現(xiàn)不少沖突堕汞,這時就要用相應(yīng)的解決方法,就是category晃琳。
這篇文章將會從幾個方向出發(fā)讯检,詳細的了解category的實現(xiàn)機制。
1. category簡介卫旱。
2. category與extension的區(qū)別
3. category如何加載并且添加到類
4. category對象關(guān)聯(lián)
category簡介
category是在2.0之后添加的特性人灼,作用是可以為存在的文件添加方法,我們列舉幾個常用的場景:
1. 模擬多繼承
2. 將私有API公開
3. 將一個類中的代碼分散出來管理
4. 私有方法
5. ......
category有很多可以挖掘的地方顾翼,下面我們就來一步一步揭開它的面紗
category與extension的區(qū)別
extension是在編譯期決定投放,category由運行期決定,這就是他們不同的根本之處适贸。它決定了他們之間的分工與區(qū)別灸芳。
extension的生命周期跟隨主類,用于隱藏私有信息拜姿,你必須擁有這個類的實現(xiàn)/源碼烙样,你才可以為它添加extension。見extension
category無法添加實例變量蕊肥,在運行期間谒获,對象內(nèi)存布局已經(jīng)確認,這時你無法破壞已經(jīng)存在的內(nèi)存空間壁却,所以無法進行實例變量的添加批狱。
category如何加載并且添加到類
在OC的runtime層中,都是用struct來表示展东,category由結(jié)構(gòu)體category_t表示赔硫,(objc-runtime-new.h中可以找到),
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; //添加的協(xié)議列表
struct property_list_t *instanceProperties; //添加的所有屬性
} category_t;
那么category如何加載盐肃?
在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的標(biāo)準下恼蓬,map_images最終會調(diào)用objc-runtime-new.mm文件中_read_images方法惊完,我們來看一下:
void _read_images(header_info **hList, uint32_t hCount)
{
...
_free_internal(resolvedFutureClasses);
}
// Discover categories.
for (EACH_HEADER) {
category_t **catlist =
_getObjc2CategoryList(hi, &count);
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;
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" : "");
}
}
if (cat->classMethods || cat->protocols
/* || 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);
}
}
}
}
// Category discovery MUST BE LAST to avoid potential races
// when other threads call the new category code before
// this thread finishes its fixups.
// +load handled by prepare_load_methods()
...
}
這里我們可以看出
- 將category的實例方法、屬性添加到主類中
- 將category的類方法添加到元類(metaclass)中
無論哪種情況处硬,最后都是通過調(diào)用static void remethodizeClass(Class cls)函數(shù)來重新整理類數(shù)據(jù)小槐。
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);
}
}
此函數(shù)的作用是將category中的方法、屬性、協(xié)議整合到主類/元類中凿跳,更新數(shù)據(jù)字段 data()中的 method_lists件豌、properties、protocols控嗜, 對于添加實例方法茧彤,則會調(diào)用 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);
}
它的工作可以看成將category的實例方法列表拼成一個實例方法列表疆栏,然后調(diào)用attachMethodLists進行處理曾掂。
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];
}
這里我們需要注意,category并沒有完全的替換掉原有類的同名方法壁顶,category的方法被放置在新方法列表的前面珠洗,而原來類的方法被放到后面,在runtime中若专,遍歷方法列表查找時许蓖,找到了category的方法后,就會停止遍歷调衰,這就是我們平時所說的“覆蓋”方法膊爪。
找到源方法很簡單,只需要遍歷方法列表嚎莉,找到最后的一個對應(yīng)名字方法即可蚁飒,(摘自:美團技術(shù)博客)
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);
}
category對象關(guān)聯(lián)
那么當(dāng)在 category 中使用對象關(guān)聯(lián),那么相應(yīng)的存儲位置萝喘,生命周期是怎么樣的?
去探索一下源碼琼懊,在objc-references.mm文件中void _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);
object->setHasAssociatedObjects();
}
} 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管理仔雷,那么它是什么呢?
/ class AssociationsManager manages a lock / hash table singleton pair.
// Allocating an instance acquires the lock, and calling its assocations()
// method lazily allocates the hash table.
spinlock_t AssociationsManagerLock;
class AssociationsManager {
// associative references: object pointer -> PtrPtrHashMap.
static AssociationsHashMap *_map;
public:
AssociationsManager() { AssociationsManagerLock.lock(); }
~AssociationsManager() { AssociationsManagerLock.unlock(); }
AssociationsHashMap &associations() {
if (_map == NULL)
_map = new AssociationsHashMap();
return *_map;
}
};
AssociationsHashMap *AssociationsManager::_map = NULL;
AssociationsManager 是一個靜態(tài)的全局 AssociationsHashMap,用來存儲所有的關(guān)聯(lián)對象驱闷,key是對象的內(nèi)存地址,value則是另一個 AssociationsHashMap雇毫,其中存儲了關(guān)聯(lián)對象的kv恒界,對象銷毀的工作則交給 objc_destructInstance
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;
}
如有錯誤請指正~
參考鏈接:
https://tech.meituan.com/DiveIntoCategory.html
http://blog.leichunfeng.com/blog/2015/05/18/objective-c-category-implementation-principle/
https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Category.html#//apple_ref/doc/uid/TP40008195-CH5-SW1 http://stackoverflow.com/questions/5272451/overriding-methods-using-categories-in-objective-c