Category
2019-07-29 本文已影响0人
石头89
Category
Category 也叫做分类,可以在不创建子类的情况下为一个类扩展功能。
Category 的作用
- 可以将一个类中的功能分组,划分到不同的 Categorys 中。
- 可以为一个类平行扩展一些功能,例如为 NSString、UIView 这些系统提供的类增加功能。
Category 和 Extension 的区别
- Category 是分类
- 用来为一个类扩展一些功能。
- 当类被 Runtime 加载时才会将 Category 的数据合并到 Class 对象中。
- Extension 是类扩展
- 常用来在 .m 文件中定义私有属性或配合 .h 文件实现对外只读但对内可读写的属性。
- 当类被编译时 Extension 就会被合并到类中。
Category 的使用
示例1:
// Person.h
//
// 定义一个类
@interface Person
@property (nonatomic, readonly, copy) NSString *no;
+ (void)initWidthNo:(NSString *)no;
@end
// Person.m
//
// Class Extension(类扩展)
// 类扩展常用来在 .m 文件中定义私有属性或配合 .h 文件实现对外只读但对内可读写的属性
@interface Person ()
@property (nonatomic, readwrite, copy) NSString *no; // 重写属性,对外只读,对内可读写
@property (nonatomic, copy) NSString *dna; // 定义一个私有属性
@end
// Person+Play.h
//
// Category(分类)
// 将 Person 的一些跟玩相关的功能放到 Play 分类中
@interface Person (Play)
- (void)playFootball();
- (void)playPingPong();
@end
// 调用示例(分类中的方法可以通过对象直接调用):
Person *person = [[Person alloc] initWidthNo:@"8888"];
person.playFootball();
person.playPingPong();
示例2:
#import <UIKit/UIKit.h>
// 为 NSString 扩展一些根据字体计算尺寸的功能
@interface NSString (StringSize)
- (CGSize)sizeWithFont:(UIFont *)font;
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)size;
- (CGSize)sizeWithAttributes:(NSDictionary *)attrs maxSize:(CGSize)size;
@end
Category 的底层实现
- Category 底层通过 struct category_t 实现,存储了方法信息、属性信息、协议信息。
- Runtime 会将 Category 的数据合并到 Class 对象和 Meta-Class 对象中。
Category 底层结构
struct _category_t {
const char *name; // 类名
classref_t cls; // 指向 Class 对象
struct method_list_t *instanceMethods; // 实例方法信息列表
struct method_list_t *classMethods; // 类方法信息列表
struct protocol_list_t *protocols; // 协议信息列表
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);
};
Category 的加载处理过程
- 通过 Runtime 加载某个类的所有 Category 的数据。
- 把所有 Category 的方法信息、属性信息、协议信息,合并到三个数组中,后编译的 Category 的数据会在数组的前面。
- 将合并后的 Category 数据(方法信息、属性信息、协议信息),插入到 Class 对象 和 Meta-Class 对象中对应的数组中的前面。
objc4 源码解读顺序:
- objc-os.mm
- _objc_init
- map_images
- map_images_nolock
- objc-runtime-new.mm
- _read_images
- remethodizeClass
- attachCategories
- attachLists
- realloc、memmove、memcpy
在 Build Phases -> Compile Source 中可以控制代码文件的编译顺序。
源码 - 1,加载某个类的所有 Category 数据
objc/Source/objc-runtime-new.mm
/***********************************************************************
* remethodizeClass
* Attach outstanding categories to an existing class.
* Fixes up cls's method list, protocol list, and property list.
* Updates method caches for cls and its subclasses.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
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);
}
}
源码 - 2,把所有 Category 的方法信息、属性信息、协议信息,合并到三个数组中
objc/Source/objc-runtime-new.mm
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order,
// oldest categories first.
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));
// 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;
}
}
auto rw = cls->data();
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
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);
}
源码 - 3,将合并后的 Category 数据插入到 Class 对象 和 Meta-Class 对象中对应的数组中的前面
objc/Project Headers/objc-runtime-new.mm
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]));
}
}