標籤:
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
上面的栗子就是把alert和block關聯起來,你關聯的什麼物件類型,取得就是什麼物件類型,然後利用取出來的對象做你想做的事,上面的栗子就是取出block,完了在block裡面做你想做的事,並且block在alert後面,使你看代碼更容易一些,(在我看來,然並卵),這個栗子也算是我從《Effective Object-c》借鑒來的,真心覺得這個自己不太好,但是對於理解對象關聯夠用了,OBJC_ASSOCIATION_RETAIN_NONATOMIC這個和(nonatomic,retain)是一樣的作用,如下表
| 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方法,我覺得博主的想法很巧妙,希望借鑒,謝謝
參考連結:http://nshipster.com/associated-objects/
http://kingscocoa.com/tutorials/associated-objects/
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Object-c Associated Object