标签:理解 effective 取出 sign 第一个 color 作用 targe bad
oc的关联的作用在我看来就是将两个对象关联起来,用的时候通过key和对象把和这个对象关联的对象再取出来(我做的项目就是和UITableView里面的一个属性关联起来了)
举个栗子:
- (void)viewDidLoad { [super viewDidLoad]; UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100, 100, 100, 100); [button setTitle:@"关联測试" forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonTap) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)buttonTap{ UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"" message:@"How (are) you doing" delegate:self cancelButtonTitle:@"Not bad" otherButtonTitles:@"Fine", nil]; void (^block)(NSInteger) = ^(NSInteger buttonIndex){ if (buttonIndex == 0) { NSLog(@"buttonIndex:0"); }else{ NSLog(@"buttonIndex:1"); } }; objc_setAssociatedObject(alert, key, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC); [alert show]; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ void (^block)(NSInteger) = objc_getAssociatedObject(alertView, key); block(buttonIndex); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
OBJC_ASSOCIATION_ASSIGN | @property (assign) or @property (unsafe_unretained) | Specifies a weak reference to the associated object. |
OBJC_ASSOCIATION_RETAIN_NONATOMIC | @property (nonatomic, strong) | Specifies a strong reference to the associated object, and that the association is not made atomically. |
OBJC_ASSOCIATION_COPY_NONATOMIC | @property (nonatomic, copy) | Specifies that the associated object is copied, and that the association is not made atomically. |
OBJC_ASSOCIATION_RETAIN | @property (atomic, strong) | Specifies a strong reference to the associated object, and that the association is made atomically. |
OBJC_ASSOCIATION_COPY | @property (atomic, copy) | Specifies that the associated object is copied, and that the association is made atomically. |
參考链接:http://nshipster.com/associated-objects/
http://kingscocoa.com/tutorials/associated-objects/
标签:理解 effective 取出 sign 第一个 color 作用 targe bad
原文地址:http://www.cnblogs.com/lytwajue/p/7039809.html