Category原理、作用
深入理解Objective-C:Category (OC1.0)
结合 category 工作原理分析 OC2.0 中的 runtime
Objective-C Associated Objects 的实现原理
关联对象 AssociatedObject 完全解析
结构基础:
struct category_t {
const char *name; // category小括号里写的名字
classref_t cls; // cls要扩展的类对象,编译期间这个值是不会有的,在app被runtime加载时才会根据name对应到类对象
struct method_list_t *instanceMethods; // 实例方法
struct method_list_t *classMethods; // 类方法
struct protocol_list_t *protocols; // category实现的protocol,比较不常用在category里面实现协议,但是确实支持的
struct property_list_t *instanceProperties; // category所有的property,这也是category里面可以定义属性的原因,不过这个property不会@synthesize实例变量,一般有需求添加实例变量属性时会采用objc_setAssociatedObject和objc_getAssociatedObject方法绑定方法绑定,不过这种方法生成的与一个普通的实例变量完全是两码事。
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties; // 类属性(@property (class,nonatomic, strong) NSString *name; 然后还需要现实+的getter setter方法,然后就可以用.号代用
method_list_t *methodsForMeta(bool isMeta) {
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};
![](https://img.haomeiwen.com/i2040445/c14ac8257582c165.png)
最后的方法:
对 Category 中方法的解析并不复杂,首先来看一下 attachCategories 的简化版代码(只有methods,properties与protocols的类似):
static void attachCategories(Class cls, category_list *cats, bool flush_caches) {
if (!cats) return;
bool isMeta = cls->isMetaClass();
method_list_t **mlists = (method_list_t **)malloc(cats->count * sizeof(*mlists));
// Count backwards through cats to get newest categories first
int mcount = 0;
int i = cats->count;
while (i--) {
auto& entry = cats->list[i];
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
mlists[mcount++] = mlist;
}
}
auto rw = cls->data();
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
rw->methods.attachLists(mlists, mcount);
free(mlists);
if (flush_caches && mcount > 0) flushCaches(cls);
}
1、首先,通过 while 循环,我们遍历所有的 category,也就是参数 cats 中的 list 属性。对于每一个 category,得到它的方法列表 mlist 并存入 mlists 中。
2、最后:rw->methods.attachLists(mlists, mcount); 把mlists放在前面,主类方法放在后面。
总结:
1、Categroy的实现,运行时先把Category中的方法遍历出来mlists,rw-> methods.attachLists(mlists, mcount),把mlists放在前面,主类方法放在后面。
2、在主类和Category中,同名方法可以同时存在,且不不是覆盖关系。运行时,当调用到同名方法,被调用的是在方法列表中排在前面的Category方法。
3、Category中,同名方法不是覆盖关系,因此还是可以想办法调用主类方法的。其途径就是获取当前对象的方法列表,从列表中找出最后一个同名方法,就是主类的方法。
4、在主类的+load方法中可以调用Category的方法,因为Category的加载是在load方法之前就完成的。对于主类和Category中都有+load的方法的时候,顺序是先主类后Category。
5、associatedObject保存变量是保存在一个全局的HashMap中,对象的地址是Key,value是另一个HashMap,这个HashMap里保存Key-Value对。
另外:
1、对系统提供的类做分类,分类是在运行时附加到相关类上的
2、对自己创建的类做分类,分类是在编译期附加到相关类上的
Runtime源码 —— 关于category的一个问题
2.关联属性的具体实现
基本用法
Category.h
@property(nonatomic,copy) NSString *name;
Category.m
- (void)setName:(NSString *)name
{
// 各个参数简单解析
// 1、self--关联的源对象
// 2、@selector(name)--关联的key
// 3、name--与对象的键键关联的值。可以通过nil来清除现有的关联。
// 4、OBJC_ASSOCIATION_COPY--关联值的内存管理策略,有如下选择:
/*
OBJC_ASSOCIATION_ASSIGN --@property(assign) / @property(unsafe_unretained)
OBJC_ASSOCIATION_RETAIN_NONATOMIC --@property(nonatomic, strong)
OBJC_ASSOCIATION_COPY_NONATOMIC --@property(nonatomic, copy)
OBJC_ASSOCIATION_RETAIN --@property(atomic, strong)
OBJC_ASSOCIATION_COPY --@property(atomic, copy)
*/
objc_setAssociatedObject(self,@selector(name),name,OBJC_ASSOCIATION_COPY);
}
- (NSString*)name
{
return objc_getAssociatedObject(self, @selector(name));
}
系统源码
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
_object_set_associative_reference(object, (void *)key, value, policy);
}
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);
// 根据传进来的value与policy,acquireValue其实只是retain或者copy
id new_value = value ? acquireValue(value, policy) : nil;
{
// AssociationsManager管理者
AssociationsManager manager;
// 获取AssociationsHashMap
AssociationsHashMap &associations(manager.associations());
disguised_ptr_t disguised_object = DISGUISE(object);
if (new_value) { //
// 获取关联的源对象self对应的ObjectAssociationMap
AssociationsHashMap::iterator i = associations.find(disguised_object);
if (i != associations.end()) {
// ObjectAssociationMap *refs就是self对应的ObjectAssociationMap
ObjectAssociationMap *refs = i->second;
ObjectAssociationMap::iterator j = refs->find(key);
if (j != refs->end()) {
// 查找key对应ObjcAssociation存在,更新new_value
old_association = j->second;
j->second = ObjcAssociation(policy, new_value);
} else {
// 查找key对应ObjcAssociation不存在,设置新的ObjcAssociation进去
(*refs)[key] = ObjcAssociation(policy, new_value);
}
} else { // ObjectAssociationMap不存在
// 设置新的ObjectAssociationMap、设置新的ObjcAssociation 保存到associations
ObjectAssociationMap *refs = new ObjectAssociationMap;
associations[disguised_object] = refs;
(*refs)[key] = ObjcAssociation(policy, new_value);
// 设置对象的has_assoc为true,标记这个对象有关联属性(对象释放时候用到这个标记)
object->setHasAssociatedObjects();
}
} else { // 传入的value是nil,就是移除这个key的关联
// 获取关联的源对象self对应的ObjectAssociationMap
AssociationsHashMap::iterator i = associations.find(disguised_object);
if (i != associations.end()) {
// 查找key对应ObjcAssociation
ObjectAssociationMap *refs = i->second;
ObjectAssociationMap::iterator j = refs->find(key);
if (j != refs->end()) {
// 持有这个ObjcAssociation,最后释放对象用
old_association = j->second;
// ObjectAssociationMap中移除ObjcAssociation
refs->erase(j);
}
}
}
}
// 如果原来的关联对象有值的话,会调用 ReleaseValue() 释放关联对象的值
if (old_association.hasValue()) ReleaseValue()(old_association);
}
在看这段代码前,我们需要先了解一下几个数据结构以及它们之间的关系:
AssociationsManager:是顶级的对象,维护了一个从 spinlock_t 锁到 AssociationsHashMap 哈希表的单例键值对映射;
AssociationsHashMap :是一个无序的哈希表,(对象地址做key :ObjectAssociationMap);
ObjectAssociationMap:是一个 C++ 中的 map ,(关联 key : ObjcAssociation);
ObjcAssociation: 是一个 C++ 的类,表示一个具体的关联结构,主要包括两个实例变量,_policy 表示关联策略,_value 表示关联对象。
每一个对象地址对应一个 ObjectAssociationMap 对象,而一个 ObjectAssociationMap 对象保存着这个对象的若干个关联记录。
![](https://img.haomeiwen.com/i2040445/351333e0ccce01f6.png)
![](https://img.haomeiwen.com/i2040445/adeb4b4d05ab3e3f.png)
objc_getAssociatedObject
id objc_getAssociatedObject(id object, const void *key) {
return _object_get_associative_reference(object, (void *)key);
}
id _object_get_associative_reference(id object, void *key) {
id value = nil;
uintptr_t policy = OBJC_ASSOCIATION_ASSIGN;
{
AssociationsManager manager;
AssociationsHashMap &associations(manager.associations());
disguised_ptr_t disguised_object = DISGUISE(object);
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()) {
// 取出对应的ObjcAssociation
ObjcAssociation &entry = j->second;
// 取出value
value = entry.value();
policy = entry.policy();
if (policy & OBJC_ASSOCIATION_GETTER_RETAIN) {
objc_retain(value);
}
}
}
}
// 这里判断get的内存策略(暂时不知道get的内存策略怎么使用,可能是系统私有使用的)
if (value && (policy & OBJC_ASSOCIATION_GETTER_AUTORELEASE)) {
objc_autorelease(value);
}
return value;
}
objc_removeAssociatedObjects
void objc_removeAssociatedObjects(id object)
{
// 判断对象、判断是否已经标记为关联对象
if (object && object->hasAssociatedObjects()) {
_object_remove_assocations(object);
}
}
_object_remove_assocations只是在Map里面for 释放关联对象的值
void _object_remove_assocations(id object) {
vector< ObjcAssociation,ObjcAllocator<ObjcAssociation> > elements;
{
AssociationsManager manager;
AssociationsHashMap &associations(manager.associations());
if (associations.size() == 0) return;
disguised_ptr_t disguised_object = DISGUISE(object);
AssociationsHashMap::iterator i = associations.find(disguised_object);
if (i != associations.end()) {
// copy all of the associations that need to be removed.
ObjectAssociationMap *refs = i->second;
for (ObjectAssociationMap::iterator j = refs->begin(), end = refs->end(); j != end; ++j) {
elements.push_back(j->second);
}
// remove the secondary table.
delete refs;
associations.erase(i);
}
}
// the calls to releaseValue() happen outside of the lock.
for_each(elements.begin(), elements.end(), ReleaseValue());
}
AssociatedObject 本身并不支持添加具备 weak 特性的 property,
但我们可以通过一个小技巧来完成:添加了一个中间角色 block,再辅以 weak 关键字就实现了具备 weak 属性的 associated object。
- (void)setContext:(NSObject*)object {
id __weak weakObject = object;
id (^block)() = ^{ return weakObject; };
objc_setAssociatedObject(self, @selector(context), block, OBJC_ASSOCIATION_COPY);
}
- (NSObject*)context {
id (^block)() = objc_getAssociatedObject(self, @selector(context));
id curContext = (block ? block() : nil);
return curContext;
}
网友评论