分类categories动态添加方法和属性

1.动态向NSObject中添加方法

@interface NSObject (CategoryWithProperty)

@property (nonatomic, strong) NSObject *property;

@end

@implementation NSObject (CategoryWithProperty)

- (NSObject *)property {

return objc_getAssociatedObject(self, _cmd);

}

- (void)setProperty:(NSObject *)value {

objc_setAssociatedObject(self, @selector(property), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

2.动态扩展属性

#import "UILabel+Associate.h"

#import 

@implementation UILabel (Associate) static char flashColorKey;

- (void) setFlashColor:(UIColor *) flashColor{

objc_setAssociatedObject(self, &flashColorKey, flashColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

- (UIColor *) getFlashColor{

return objc_getAssociatedObject(self, &flashColorKey);

}

@end

你可能感兴趣的:(类扩展)