Category模式用于向已经存在的类添加方法从而达到扩展已有类的目的,在很多情形下Category也是比创建子类更优的选择。新添加的方法同样也会被被扩展的类的所有子类自动继承。
如果我们能在Category中添加自定义的属性那岂不是更好。
属性其实就是set/get函数,下面直接上代码:
使用前请注意导入 #import <objc/runtime.h>
使用下面两个函数
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
我们定义一个Category,
UIImageView+PropertyDemo.h
@interface UIImageView (PropertyDemo)
- (void) setStyle:(NSObject*) style;
- (NSObject *) getStyle;
@end
UIImageView+PropertyDemo.m
@implementation UIImageView (PropertyDemo)
static char styleKey;
- (void) setStyle:(NSObject *) style
{
objc_setAssociatedObject(self, &styleKey, style, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIColor *) getStyle
{
return objc_getAssociatedObject(self, &styleKey);
}
@end
外部调用:
UIImageView *mImageView = [UIImageView alloc]initWithImage:[UIImage imageNamed:@"image.png"]];
mImageView.style = @"style0";
NSLog(@"The style is %@",mImageView.style);
转载请留名:http://blog.csdn.net/yan_daoqiu/article/details/50350524