void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) id objc_getAssociatedObject(id object, const void *key)原理详细参见官方的https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html
首先导入头文件:#import <objc/runtime.h>
示例一
看一个类别和动态添加属性的例子:
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;//设置 key
- (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]);
------------------------------
示例二
static char overviewKey;//设置 key
- (IBAction)showAlertAction:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"warn" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
objc_setAssociatedObject(alert, &overviewKey, @"test", OBJC_ASSOCIATION_RETAIN);
[alert show];
[alert release];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
NSLog(@"== : %@",objc_getAssociatedObject(alertView, &overviewKey));
}
}
打印输出
test