美文网首页
iOS关联对象 objc_setAssociatedObje

iOS关联对象 objc_setAssociatedObje

作者: 黄卷青灯空离别 | 来源:发表于2018-01-23 17:05 被阅读25次
    首先看一下此方法接收的参数
    objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
    
    被关联的对象,下面举的例子中关联到了UIAlertView
    - 1. 要关联的对象的键值,一般设置成静态的,用于获取关联对象的值
    - 2. 要关联的对象的值,从接口中可以看到接收的id类型,所以能关联任何对象
    - 3. 关联时采用的协议,有assign,retain,copy等协议,具体可以参考官方文档
    
    下面就以UIAlertView为例子简单介绍一下使用方法

    使用场景:在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_setAssociatedObje

          本文链接:https://www.haomeiwen.com/subject/guosaxtx.html