runtime只是针对于系统类,添加属性让属性与对象产生关联。
给category动态添加属性,
分类中添加:
//只声明setter、getter方法,未实现setter、getter方法
@property (nonatomic,copy) NSString *testName;
实现setter方法:
- (void)setTestName:(NSString *)testName
{
/*
object : 给相应对象添加属性
key : 属性名称
value : 属性值
policy :保存策略
*/
objc_setAssociatedObject(self, "testName", testName, OBJC_ASSOCIATION_COPY);
}
实现getter方法:
- (NSString *)testName
{
return objc_getAssociatedObject(self, "testName");
}
如果添加基础数据类型的属性,则要做类型转换
- (void)setTestNum:(NSInteger)testNum
{
//1.
//objc_setAssociatedObject(self, "testNum", [NSNumber numberWithInteger:testNum], OBJC_ASSOCIATION_ASSIGN);
//2.
objc_setAssociatedObject(self, @selector(testNum), [NSNumber numberWithInteger:testNum], OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)testNum
{
//return (NSInteger)objc_getAssociatedObject(self, "testNum");
return (NSInteger)objc_getAssociatedObject(self, _cmd);
}