基础使用
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, const void *key)
key是一个地址值,随便用一个不会重复的地址即可, 例如:
objc_getAssociatedObject(self, _cmd)
static const char Key;
id objc_getAssociatedObject(self, &Key)
原理
有一个AssociationsManager类,持有一个AssociationsHashMap类型的类变量, key由对象的地址经过运算后生成, 是传入的object的地址, value是一个ObjectAssociationMap类型的hash表, key是传入的key, value是一个ObjcAssociation类型的值, ObjcAssociation有两个实例变量_policy和_value, 对应传入的, policy和value
对object不会有强引用,但是对value会有强引用
policy有哪些策略
/* Associative References */
/**
* Policies related to associative references.
* These are options to objc_setAssociatedObject()
*/
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
* The association is not made atomically. */
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.
* The association is not made atomically. */
OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.
* The association is made atomically. */
OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied.
* The association is made atomically. */
};
能不能关联一个weak修饰的属性
不能直接关联, 因为没有weak对应的policy, 但是可以用间接的方式达到目的 利用OBJC_ASSOCIATION_RETAIN_NONATOMIC关联一个对象,在这个中间对象中,再利用weak修饰一个属性, 获取值的时候, 拿这个中间对象的weak属性
demo
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface WYFood: NSObject
@end
@implementation WYFood
@end
@interface WYIndirectClass : NSObject
@property (nonatomic, weak) WYFood *food;
@end
@implementation WYIndirectClass
@end
@interface WYAnimal: NSObject
@end
@implementation WYAnimal
@end
@interface WYAnimal(Eat)
@property (nonatomic, weak) WYFood *food;
@end
@implementation WYAnimal(Eat)
- (void)setFood:(WYFood *)food {
WYIndirectClass *res = objc_getAssociatedObject(self, @selector(food));
if(res == nil) {
res = [WYIndirectClass new];
objc_setAssociatedObject(self, @selector(food), res, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
res.food = food;
}
- (WYFood *)food {
WYIndirectClass *res = objc_getAssociatedObject(self, _cmd);
return res.food;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
WYAnimal *animal = [WYAnimal new];
{
WYFood *food = [WYFood new];
animal.food = food;
NSLog(@"%@", animal.food);
}
NSLog(@"%@", animal.food);
}
return 0;
}
源码
class ObjcAssociation {
uintptr_t _policy;
id _value;
}
typedef DenseMap<const void *, ObjcAssociation> ObjectAssociationMap;
typedef DenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap> AssociationsHashMap;
class AssociationsManager {
using Storage = ExplicitInitDenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap>;
static Storage _mapStorage;
public:
AssociationsManager() { AssociationsManagerLock.lock(); }
~AssociationsManager() { AssociationsManagerLock.unlock(); }
AssociationsHashMap &get() {
return _mapStorage.get();
}
static void init() {
_mapStorage.init();
}
};
id _object_get_associative_reference(id object, const void *key)
{
ObjcAssociation association{};
{
AssociationsManager manager;
AssociationsHashMap &associations(manager.get());
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();
}
void _object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
{
// This code used to work when nil was passed for object and key. Some code
// probably relies on that to not crash. Check and handle it explicitly.
// rdar://problem/44094390
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));
DisguisedPtr<objc_object> disguised{(objc_object *)object};
ObjcAssociation association{policy, value};
// retain the new value (if any) outside the lock.
association.acquireValue();
bool isFirstAssociation = false;
{
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 */
isFirstAssociation = true;
}
/* 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);
}
}
}
}
}
// Call setHasAssociatedObjects outside the lock, since this
// will call the object's _noteAssociatedObjects method if it
// has one, and this may trigger +initialize which might do
// arbitrary stuff, including setting more associated objects.
if (isFirstAssociation)
object->setHasAssociatedObjects();
// release the old value (outside of the lock).
association.releaseHeldValue();
}