标签:
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
使用场景:在UITableView中点击某一个cell,这时候弹出一个UIAlertView,然后在UIAlertView消失的时候获取此cell的信息,我们就获取cell的indexPath
#import <objc/runtime.h>
static char kUITableViewIndexKey;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
......
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"这里是xx楼"
delegate:self
cancelButtonTitle:@"好的"
otherButtonTitles:nil];
//然后这里设定关联,此处把indexPath关联到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);
}
}
iOS中关联对象的简单使用objc_setAssociatedObject
标签:
原文地址:http://www.cnblogs.com/cqcnblogs/p/5796462.html