如果为某一个类添加一个属性有时候需要使用运行时的方式添加
Associate:关联
//设置关联对象
void
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
id _Nullable value, objc_AssociationPolicy policy)
//获取关联对象
id _Nullable
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
设置关联对象
参数说明涉及:
object :关联对象的目标
key :关联对象的键值
value : 要添加的关联对象,如果我们添加int型属性则必须把 参数封装成对象的形式
policy :保存对象的策略,数值型使用OBJC_ASSOCIATION_ASSIGN,字符串使用OBJC_ASSOCIATION_COPY等
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. */
};
//获取关联对象
获取关联对象需要使用运行时的方式根据关联对象的键值方式取出对象, 然后根据返回的结果 把对象转化为需要的返回的数据类型
其中
实例如下:
#import "WBDetailBaseTemplateModel.h"
@interface WBDetailBaseTemplateModel (Extension)
@property (nonatomic,assign) int style;
@end
#import "WBDetailBaseTemplateModel+Extension.h"
#import <objc/runtime.h>
char* const ASSOCIATION_style = "ASSOCIATION_style";
@implementation WBDetailBaseTemplateModel (Extension)
#pragma mark 运行时添加属性
-(void)setStyle:(int)style{
objc_setAssociatedObject(self,ASSOCIATION_style,@(style),OBJC_ASSOCIATION_ASSIGN);
}
-(int)style{
return [objc_getAssociatedObject(self,ASSOCIATION_style) intValue ];
}
@end
网友评论