(Objective-C) 通过关联对象给分类添加成员变量
2022-06-12 本文已影响0人
布呐呐u
- 使用给定的键和关联策略为指定对象设置关联值
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
id _Nullable value, objc_AssociationPolicy policy)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
- 返回与给定键的指定对象关联的值
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
- Example
// set method
- (void)setTestName:(NSString *)testName {
objc_setAssociatedObject(self, @selector(testName), testName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
// get method
- (NSString *)testName {
return objc_getAssociatedObject(self, _cmd);
}
// dealloc
- (void)dealloc {
objc_removeAssociatedObjects(self);
}
objc_AssociationPolicy
-
OBJC_ASSOCIATION_ASSIGN
(assign) -
OBJC_ASSOCIATION_RETAIN_NONATOMIC
(strong,nonatomic) -
OBJC_ASSOCIATION_COPY_NONATOMIC
(copy, nonatomic) -
OBJC_ASSOCIATION_RETAIN
(strong, atomic) -
OBJC_ASSOCIATION_COPY
(copy, atomic)