一勺择、Category概念?
Category
是Objective-C 2.0之后添加的語(yǔ)言特性谬莹,分類陋率、類別其實(shí)都是指的Category
教翩。Category
的主要作用是為已經(jīng)存在的類添加方法沛简。
可以把類的實(shí)現(xiàn)分開在幾個(gè)不同的文件里面齐鲤,這樣做有幾個(gè)好處,如下
- 1.減少單個(gè)文件的體積
- 2.把不同的功能組織到不同的category里
- 3.由多個(gè)開發(fā)者共同完成一個(gè)類
- 4.按需加載想要的category
- 5.聲明私有方法
二椒楣、Category源碼分析
RMPerson
#import <Foundation/Foundation.h>
@interface RMPerson : NSObject
@end
#import "RMPerson.h"
@implementation RMPerson
@end
RMPerson+(Test)
#import "RMPerson.h"
@interface RMPerson (Test) <NSCopying>
- (void)text;
+ (void)text1;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) double weight;
@end
----------------------------------------------------------
#import "RMPerson+Test.h"
@implementation RMPerson (Test)
- (void)text {
NSLog(@"TEST---111111111111");
}
+ (void)text1 {
NSLog(@"TEST---222222222222");
}
@end
RMPerson類和RMPerson分類-RMPerson+(Test)给郊,我們通過xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc RMPerson+(Test).m
將RMPerson+(Test)
轉(zhuǎn)換成C/C++源碼。窺探下源碼的內(nèi)容(由于內(nèi)容比較多捧灰,上重要的部分)
分類結(jié)構(gòu)體
struct _category_t {
const char *name; //類名稱
struct _class_t *cls; //類指針
const struct _method_list_t *instance_methods; //對(duì)象方法列表
const struct _method_list_t *class_methods; //類方法列表
const struct _protocol_list_t *protocols; //協(xié)議方法列表
const struct _prop_list_t *properties; //屬性列表
};
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
// 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;
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 || (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);
}
}
}
}
}
由上面源碼我們閱讀可得出
- 1.將分類的對(duì)象方法淆九、對(duì)象協(xié)議方法、對(duì)象屬性整理到類對(duì)象中
- 2.將分類的類方法整理到元類對(duì)象中
而從源碼中毛俏,我們可注意到炭庙,無(wú)論哪種整理都是通過調(diào)用static void remethodizeClass(Class cls)
函數(shù)來重新整理類的數(shù)據(jù),下面我們來看看remethodizeClass
函數(shù)如何整理類信息
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);
}
}
這個(gè)函數(shù)的主要作用是將 Category 中的方法、屬性和協(xié)議整合到類(主類或元類)中煌寇,然后通過數(shù)據(jù)字段 data() 得到類對(duì)象里面的數(shù)據(jù)焕蹄,將 所有分類的對(duì)象方法、屬性阀溶、協(xié)議腻脏,通過attachCategoryMethods函數(shù)附加到類對(duì)象的方法列表中
鸦泳,而attachCategoryMethods
函數(shù)才是正在處理Category方法的
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)); // 協(xié)議列表
// 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];
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
mlists[mcount++] = mlist; // 從最后編譯的分類開始取出
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
proplists[propcount++] = proplist;
}
protocol_list_t *protolist = entry.cat->protocols;
if (protolist) {
protolists[protocount++] = protolist;
}
}
// 得到類對(duì)象里面的數(shù)據(jù)
auto rw = cls->data();
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
// 將所有分類的對(duì)象方法,附加到類對(duì)象的方法列表中
rw->methods.attachLists(mlists, mcount);
free(mlists);
if (flush_caches && mcount > 0) flushCaches(cls);
// 將所有分類的屬性永品,附加到類對(duì)象的屬性列表中
rw->properties.attachLists(proplists, propcount);
free(proplists);
//將所有分類的協(xié)議做鹰,附加到類對(duì)象的協(xié)議中
rw->protocols.attachLists(protolists, protocount);
free(protolists);
}
attachLists函數(shù)
里主要的是memmove函數(shù)
和memcpy函數(shù)
,memmove函數(shù)
將原來的方法往后移動(dòng)了addedCount(分類的方法數(shù)量)
個(gè)位置鼎姐,memcpy函數(shù)
將分類的方法添加到原來類方法列表的位置钾麸,這樣就完美將分類的方法、協(xié)議症见、屬性添加到了類信息中
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;
// array()->lists 原來的方法列表
memmove(array()->lists + addedCount,
array()->lists,
oldCount * sizeof(array()->lists[0]));
// addedLists 所有分類的方法列表
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]));
}
}
貼一下源碼的閱讀順序喂走,有興趣的同學(xué)可以下載源碼閱讀一下:
源碼解讀順序,如下
- objc-os.mm
- _objc_init
- map_images
- map_images_nolock
- objc-runtime-new.mm
- _read_images
- remethodizeClass
- attachCategories
- attachLists
- realloc谋作、memmove芋肠、 memcpy