objective c, category 和 protocol 中添加property

property的本质是实例变量 + getter 和 setter 方法

category和protocol可以添加方法

category 和 protocol中可以添加@property 关键字

所以,在protocol中添加property时,其实就是添加了 getter 和 setter 方法,在实现这个protocol的类中,我们要自己手动添加实例变量

例: @synthesize name = _name; //此行代码即添加了实例变量及实现了protocol中属性的getter、setter方法

 

在category中添加property时, 在@implentation添加 getter 和 setter方法时, 由于category不能添加实例变量,故必须通过运行时添加associated object的方法来添加实例变量

例:

#import "UIImage+category.h" static const void *tagKey = &tagKey; @implementation UIImage (category) - (NSString *)tag { return objc_getAssociatedObject(self, tagKey); } - (void)setTag:(NSString *)tag { objc_setAssociatedObject(self, tagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC); } @end

http://www.jianshu.com/p/00f84e05be49 

你可能感兴趣的:(objective c, category 和 protocol 中添加property)