objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
有4個(gè)參數(shù)? ?
1.關(guān)聯(lián)的對(duì)象
2.要關(guān)聯(lián)的對(duì)象的key
3.要關(guān)聯(lián)的對(duì)象的key對(duì)應(yīng)的value
4.要關(guān)聯(lián)的對(duì)象?采用的協(xié)議? ??有assign签钩,retain,copy等協(xié)議
下面就以UIAlertView為例子簡(jiǎn)單介紹一下使用方法
使用場(chǎng)景:在UITableView中點(diǎn)擊某一個(gè)cell饿敲,這時(shí)候彈出一個(gè)UIAlertView喜德,然后在UIAlertView消失的時(shí)候獲取此cell的信息,我們就獲取cell的indexPath
第一步:
#import
static char kUITableViewIndexKey;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
......
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? message:@"這里是xx樓"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? delegate:self
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? cancelButtonTitle:@"好的"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? otherButtonTitles:nil];
//然后這里設(shè)定關(guān)聯(lián)墙歪,此處把indexPath關(guān)聯(lián)到alert上
objc_setAssociatedObject(alert, &kUITableViewIndexKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[alert show];
}
第二步:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
? ? if (buttonIndex == 0) {
? ? NSIndexPath *indexPath = objc_getAssociatedObject(alertView, &kUITableViewIndexKey);
? ? NSLog(@"%@", indexPath);
? ? }
}?