oc的關聯的作用在我看來就是將兩個對象關聯起來,用的時候在取出來(我做的項目就是和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. 而且,用block還要注意循環引用的問題,這個在這裡就不多說了,我個人認為http://kingscocoa.com/tutorials/associated-objects/這個寫的不錯,是全英文的,不過不難,建議可以看看,理解問題會更上一層樓,這個博客講解了為什麼用關聯,舉得栗子就是正常寫的情況下,記錄你要刪除的cell的IndexPath,會把這個IndexPath弄成全局變量來記錄,完了操作刪除,但是要想到一個問題就是我要是在其他地方也操作這個值不就會亂套麼,或者我就用一次,用全局變量就太麻煩了,所以索性用關聯記錄這個值,於是可以模仿我上面的栗子寫,不過博主用了三種方法闡述,第一個就是想我上面栗子一樣正常寫,第二種就是給NSObject加拓展方法,傳入對象和關聯的值,第三種就是給UIALertView加類方法,把IndexPath設置成屬性,重寫setter和getter方法,我覺得博主的想法很巧妙,希望借鑒,謝謝