前言
本文已经加入专辑《彻底弄懂OC系列》。
相关问题
- Category的基本使用
- Category的合并原理
- Category与Extension的区别
基本使用
- Category可以为类增加类方法、实例方法。
- Category可以为类增加协议。
- Category可以为类增加属性,但需要自己实现存取逻辑。
- Category中的类方法或者实例方法如果与原类中的方法同名,则优先调用Category类中的方法。
- 同一个类多个Category中有相同的方法,则按照编译顺序,后编译的先调用。
- Category中的方法会在运行时和原类进行合并。

如上图,我们为Person类增加了两个分类,Eat和Test,并且编译顺序是先编译Eat 再编译 Test。
@interface Person (Test)<NSCopying>
@property (nonatomic, assign)int age;
- (void)test;
+ (void)test2;
- (void)speak;
@end
@implementation Person (Test)
@dynamic age;
- (void)test {
NSLog(@"test");
}
+ (void)test2 {
NSLog(@"test2");
}
- (void)speak {
NSLog(@"Person (Test) -- speak");
}
-(id)copyWithZone:(NSZone *)zone {
return [[Person alloc] init];
}
@end
从Person (Test)中可以看出,我们可以为Category增加类方法:+ (void)test2 、实例方法:- (void)test、 协议:<NSCopying> 、属性:age。
@interface Person (Eat)
- (void)eat;
- (void)speak;
@end
@implementation Person (Eat)
- (void)eat {
NSLog(@"eat");
}
- (void)speak {
NSLog(@"Person (Eat) -- speak");
}
@end
@interface Person : NSObject
- (void)run;
- (void)speak;
@end
@implementation Person
- (void)run {
NSLog(@"run");
}
- (void)speak {
NSLog(@"Person -- speak");
}
@end
我们在Person、Person(Eat)、Person(Test) 都实现了方法-(void)speak() 我们在如下调用的时候:
Person *person = [[Person alloc] init];
[person speak];
//输出
Person (Test) -- speak
因为Person(Test)是后编辑的,所以,调用的是Person(Test)里面的speak方法。
了解了上述用法之后,我们需要关注的是Category的实现原理。我们都听说过,Category是在运行时实现的,那它是如何实现的呢?
实现原理
我们将Person(Test)编译成C代码之后可以发现,分类被编译成了_category_t类型的结构体实例。可见Category的底层实现是_category_t。
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,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_Person_$_Test,
(const struct _protocol_list_t *)&_OBJC_CATEGORY_PROTOCOLS_$_Person_$_Test,
(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_Person_$_Test,
};
struct _category_t {
const char *name; //Category name
struct _class_t *cls; // class
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; //属性
};
以我们的例子来看,运行时时期有两个struct _category_t 类型的结构体实例,分别是Person(Eat)和Person(Test),还有元类Person对象,它也是一个结构体不过类型是Struct Person_IMP。在运行时初始化的时候会将分类中的内容与原类中的内容进行合并,我们以实例方法为例,画出他们的合并过程。

起初的时候Person类的实例方法中防着它自己的实例方法m1,m1是一个数组,它里面的内容是Person原类中的实例方法。然后在运行时先将分类合并Person(Eat) 和 Person(Test)。然后将Person中的methods与分类的合并结果再次合并,形成如上图的结构。
从上图中我们可以看出,当调用speak方法的时候,从methods里面查找,先中m3就就找到了Person(Test)类中的speak方法,所以后面m2 m1中的方法不会被调用。
理解源码
// objc-os.mm/_objc_init(void) 引导程序初始化。
void _objc_init(void)
{
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
//objc-runtime-new.mm/void map_images
void map_images(unsigned count, const char * const paths[],
const struct mach_header * const mhdrs[])
{
rwlock_writer_t lock(runtimeLock);
return map_images_nolock(count, paths, mhdrs);
}
// objc-os.mm/void map_images_nolock
void map_images_nolock(unsigned mhCount, const char * const mhPaths[],
const struct mach_header * const mhdrs[])
{
if (hCount > 0) {
_read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
}
}
//objc-runtime-new.mm/void _read_images
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;
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;
}
}
}
}
}
//objc-runtime-new.mm/static void remethodizeClass
static void remethodizeClass(Class cls)
{
// Re-methodizing: check for more categories
if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
attachCategories(cls, cats, true /*flush caches*/);
free(cats);
}
}
//objc-runtime-new.mm/static void attachCategories 核心合并方法
static void attachCategories(Class cls, category_list *cats, bool flush_caches)
{
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--) {
//遍历cats->list
auto& entry = cats->list[i];
//取出Category里方法
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
mlists[mcount++] = mlist;
fromBundle |= entry.hi->isBundle();
}
}
// 取出类里面的数据 rw->methods 里面取 类里面的方法
auto rw = cls->data();
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
// 将分类的附加到原类的methods
rw->methods.attachLists(mlists, mcount);
}
// objc-runtime-new.h/void attachLists
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]));
}
}
Category与Extension的区别
从上面的讲述我们可以知道,Category是通过运行时机制实现的。而Extension是在编译阶段将Extension与原类进行合并的。