美文网首页
Category 中通过runtime添加属性

Category 中通过runtime添加属性

作者: 海子_天空 | 来源:发表于2022-01-10 16:15 被阅读0次

1、在Category中声明一个属性。

@property (nonatomic, strong) NSString *name;

2、声明一个Key。

NSString *const KeyName = @"KeyName";

3、实现属性的Get、Set方法。

-(NSString *)name{
return objc_getAssociatedObject(self, &KeyName);
}
-(void)setName:(NSString *)name {
objc_setAssociatedObject(self, &KeyName, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

4、成功实现,在Category中想用的位置就可以使用了。

self.name = @"张三";

相关文章

网友评论

      本文标题:Category 中通过runtime添加属性

      本文链接:https://www.haomeiwen.com/subject/vtgmcrtx.html