首先来思考几个问题:api
先来回答第一个问题,定义@property的事情,系统为咱们作了如下事情:markdown
咱们能够尝试在分类中 定义 @property,会发现,getter 和 setter 仅仅是被声明,可是没有实现,并且成员变量 _property 也没有被声明。ide
那咱们能够尝试本身声明 _property 而且重写 getter 和 setter,发现没法声明 _property,会报错。函数
所以能够得出结论:Category中没法定义@propertyui
咱们看一下 category_t 这个结构体this
struct category_t {
const char *name;
classref_t cls;
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);
protocol_list_t *protocolsForMeta(bool isMeta) {
if (isMeta) return nullptr;
else return protocols;
}
};
复制代码
很明显能够看出,这里没有存储成员变量的地方。spa
若是咱们定义了一个 @property,而后直接对其进行赋值或者取值操做,程序会直接崩溃。ssr
崩溃的缘由是 unrecognized selector,可见 get 和 set 方法并无被实现。code
若是须要在分类中使用 @property,最简单的方法就是使用关联对象,大体用法以下:
这里对用法不做过多的介绍,不了解的同窗能够自行查阅orm
- (NSString *)personParam {
return objc_getAssociatedObject(self, _cmd);
}
- (void)setPersonParam:(NSString *)personParam {
objc_setAssociatedObject(self, @selector(personParam), personParam, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
复制代码
接下来咱们仍是从源码入手,解析一下原理
首先咱们找到 objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) 函数,发现最后的实现调用的是 _object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
这个函数。咱们点进去一探究竟。
void
_object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
{
// 防止crash
if (!object && !value) return;
if (object->getIsa()->forbidsAssociatedObjects())
_objc_fatal("objc_setAssociatedObject called on instance (%p) of class %s which does not allow associated objects", object, object_getClassName(object));
// 这里对 objc_object 进行了一次封装,
DisguisedPtr<objc_object> disguised{(objc_object *)object};
ObjcAssociation association{policy, value};
// retain the new value (if any) outside the lock.
// 调用 retain 或者 copy 等
association.acquireValue();
{
AssociationsManager manager;
AssociationsHashMap &associations(manager.get());
if (value) {
auto refs_result = associations.try_emplace(disguised, ObjectAssociationMap{});
if (refs_result.second) {
/* it's the first association we make */
object->setHasAssociatedObjects();
}
/* establish or replace the association */
auto &refs = refs_result.first->second;
auto result = refs.try_emplace(key, std::move(association));
if (!result.second) {
association.swap(result.first->second);
}
} else {
auto refs_it = associations.find(disguised);
if (refs_it != associations.end()) {
auto &refs = refs_it->second;
auto it = refs.find(key);
if (it != refs.end()) {
association.swap(it->second);
refs.erase(it);
if (refs.size() == 0) {
associations.erase(refs_it);
}
}
}
}
}
// release the old value (outside of the lock).
association.releaseHeldValue();
}
复制代码
能够看出,存储关联对象的结构应该是 Map。
这里的代码较为复杂,咱们能够换个思路,先把一些核心的类和结构体进行一次解析。咱们能够找到几个关键的类
上文中声明了一个 AssociationsManager 类型的变量 manager,而且调用了 get() 方法,咱们进入该类
class AssociationsManager {
using Storage = ExplicitInitDenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap>;
static Storage _mapStorage;
public:
// 这里能够看到,在该对象的生命周期范围内,是加了锁的
AssociationsManager() { AssociationsManagerLock.lock(); }
~AssociationsManager() { AssociationsManagerLock.unlock(); }
// 这里是get方法,咱们能够看到返回值是AssociationsHashMap类型
AssociationsHashMap &get() {
return _mapStorage.get();
}
static void init() {
_mapStorage.init();
}
};
复制代码
typedef DenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap> AssociationsHashMap;
复制代码
这个类的实现比较多,咱们先看其中一部分
class ObjcAssociation {
uintptr_t _policy;
id _value;
public:
};
复制代码
这两个值就很是眼熟了,就是咱们调用runtime的api的时候传进来的 policy 和 value。
至此,咱们能够梳理一下大体的结构了:
一样的咱们从runtime源码入手,搜索 objc_getAssociatedObject(id object, const void *key),最终会进入 id _object_get_associative_reference(id object, const void *key) 这个函数,让咱们去这个函数里一探究竟。
id
_object_get_associative_reference(id object, const void *key)
{
ObjcAssociation association{};
{
// 又是咱们熟悉的manager
AssociationsManager manager;
// 又是咱们熟悉的AssicuationsHashMap
AssociationsHashMap &associations(manager.get());
// 这里利用迭代器,先找到 object 对应的ObjectAssociationMap
AssociationsHashMap::iterator i = associations.find((objc_object *)object);
if (i != associations.end()) {
ObjectAssociationMap &refs = i->second;
ObjectAssociationMap::iterator j = refs.find(key);
if (j != refs.end()) {
association = j->second;
association.retainReturnedValue();
}
}
}
return association.autoreleaseReturnedValue();
}
复制代码
很简单就能够看出,他是一层一层,取出最终的value,而后 return 出去。
至此,Category 的系列文章都已经写完了,相信你们对分类都已经有了一个比较深的认识。可是但愿你们能够多多上手,只有实践过才能把知识转化为本身的。
文中若有错误,欢迎指出。