使用运行时库,必须要先引入 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)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
UILabel+Associate.h
#import <UIKit/UIKit.h>
@interface UILabel (Associate)
- (void) setFlashColor:(UIColor *) flashColor;
- (UIColor *) getFlashColor;
@end
UILabel+Associate.m
#import "UILabel+Associate.h"
#import <objc/runtime.h>
@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
调用代码
UILabel *lab = [[UILabel alloc] init];
[lab setFlashColor:[UIColor redColor]];
NSLog(@"%@", [lab getFlashColor]);