轉(zhuǎn)自 http://www.cnblogs.com/cqcnblogs/p/5796462.html
首先看一下此方法接收的參數(shù)
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
被關(guān)聯(lián)的對(duì)象,下面舉的例子中關(guān)聯(lián)到了UIAlertView
要關(guān)聯(lián)的對(duì)象的鍵值,一般設(shè)置成靜態(tài)的,用于獲取關(guān)聯(lián)對(duì)象的值
要關(guān)聯(lián)的對(duì)象的值,從接口中可以看到接收的id類型,所以能關(guān)聯(lián)任何對(duì)象
關(guān)聯(lián)時(shí)采用的協(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);
}
}