分類是什么
Category是Objective-C 2.0之后添加的語言特性含鳞,分類、類別其實(shí)都是指的Category。Category的主要作用是為已經(jīng)存在的類添加方法。
Objective-C 中的 Category 就是對(duì)裝飾模式的一種具體實(shí)現(xiàn)傍菇。它的主要作用是在不改變?cè)蓄惖那疤嵯麓昊希瑒?dòng)態(tài)地給這個(gè)類添加一些方法仰挣。
struct category_t {
const char *name;//分類名稱
classref_t cls;//宿主類
struct method_list_t *instanceMethods;//實(shí)例方法列表
struct method_list_t *classMethods;//類方法列表
struct protocol_list_t *protocols;//協(xié)議列表
struct property_list_t *instanceProperties;//屬性的列表
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties;
method_list_t *methodsForMeta(bool isMeta) {
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};
通過分類結(jié)構(gòu)可以知道可以為分類添加那些內(nèi)容(類方法饭于,實(shí)例方法,協(xié)議撬码,屬性)
注意為類別添加屬性時(shí)用關(guān)聯(lián)的方式
static char *nameKey = "name";
@implementation NSString (THString)
-(void)setName:(NSString *)name{
objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_COPY);
}
-(NSString *)name{
return objc_getAssociatedObject(self, nameKey);
}
分類做了什么
聲明私有方法
分解體積龐大的類文件
把framework的私有方法公開
分類特點(diǎn)
運(yùn)行時(shí)決議:編好分類文件之后儿倒,并沒有把分類中添加的內(nèi)容附加到宿主類上,而是運(yùn)行時(shí)通過runtime把分類中的內(nèi)容添加到宿主類中
給系統(tǒng)類添加分類
源碼分析
static void remethodizeClass(Class cls)
{
category_list *cats;
bool isMeta;
runtimeLock.assertLocked();
//這里拿實(shí)例方法的添加邏輯來分析 isMeta = NO
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);
}
}
//將所有的分類拼接到所屬的宿主類中
static void
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
if (!cats) return;//分類判空
if (PrintReplacedMethods) printReplacements(cls, cats);
bool isMeta = cls->isMetaClass();
//method_list_t 是二維數(shù)組 [[method_t, method_t....],[method_t],[method_t, method_t, method_t,........]]
// 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;//宿主類分類的總數(shù)
bool fromBundle = NO;
while (i--) {//倒序遍歷,最先訪問最后編譯的分類
// 獲取一個(gè)分類
auto& entry = cats->list[i];
//獲取分類方法列表
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
// 最后編譯的分類最先添加到分類數(shù)組中
mlists[mcount++] = mlist;
fromBundle |= entry.hi->isBundle();
}
//獲取屬性列表
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
proplists[propcount++] = proplist;
}
//獲取協(xié)議列表
protocol_list_t *protolist = entry.cat->protocols;
if (protolist) {
protolists[protocount++] = protolist;
}
}
// 獲取宿主類中rw的數(shù)據(jù)呜笑,其中包含宿主類的方法列表信息
auto rw = cls->data();
//針對(duì)分類中有關(guān)內(nèi)存管理方法情況下的一些特殊處理
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
/*
rw 代表類
mlists 類的方法列表
attachLists 將mcount個(gè)元素的方法列表拼接到rw的methods
*/
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);
}
//將mcount個(gè)元素的方法列表拼接到rw的methods
void attachLists(List* const * addedLists, uint32_t addedCount) {
if (addedCount == 0) return;
if (hasArray()) {
// many lists -> many lists
uint32_t oldCount = array()->count;//列表中原有的列表總數(shù)
uint32_t newCount = oldCount + addedCount;//拼接之后元素總數(shù)
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));//根據(jù)總數(shù)從新分配內(nèi)存
array()->count = newCount;//重新設(shè)置元素總數(shù)
/*
內(nèi)存移動(dòng)
[[新元素],...[],[原先的元素],[原先的元素]......]
宿主類在分類方法后面夫否,故宿主類被分類方法所替代
*/
memmove(array()->lists + addedCount, array()->lists,
oldCount * sizeof(array()->lists[0]));
//內(nèi)存拷貝
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]));
}
}
源碼總結(jié)
分類中的方法可以替換宿主類中的方法
同名分類方法誰能編譯取決于編譯順序(誰后編譯誰先執(zhí)行)
名字相同的分類會(huì)引起編譯錯(cuò)誤
擴(kuò)展(Extension)
擴(kuò)展作用:
生成私有屬性
生成私有成員變量
生成私有方法
特點(diǎn)
編譯時(shí)決議
只以聲明的形式存在,多數(shù)情況下寄生于宿主類的.m中(可以理解為內(nèi)部的私有聲明)
不能為系統(tǒng)類添加擴(kuò)展
這里也可以作為分類與擴(kuò)展的區(qū)別:
分類是運(yùn)行時(shí)決議叫胁,拓展是編譯時(shí)決議
分類既有聲明也有實(shí)現(xiàn)凰慈,擴(kuò)展只能聲明
分類能為系統(tǒng)類添加分類,擴(kuò)展則不可以