您的位置:首页 > 移动开发 > IOS开发

两对象的关联

2016-04-01 16:17 477 查看
1.基本资料

//policy  

enum {  

    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */  

    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 

                                            *   The association is not made atomically. */  

    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 

                                            *   The association is not made atomically. */  

    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object. 

                                            *   The association is made atomically. */  

    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied. 

                                            *   The association is made atomically. */  

};  

  

/// Type to specify the behavior of an association.  

typedef uintptr_t objc_AssociationPolicy;  

  

  

  

  

  

//method  

void objc_setAssociatedObject(id object, const voidvoid *key, id value, objc_AssociationPolicy policy)  

  

id objc_getAssociatedObject(id object, const voidvoid *key)  

  

void objc_removeAssociatedObjects(id object)
 

关联的方式
OBJC_ASSOCIATION_ASSIGN 弱引用
OBJC_ASSOCIATION_RETAIN_NONATOMIC
强类型引用并原子安全性

OBJC_ASSOCIATION_COPY_NONATOMIC copy内容并创建新地址

OBJC_ASSOCIATION_RETAIN 

OBJC_ASSOCIATION_COPY

2.基本概念
把一个value关联到另外一个object里,类似NSDictionary的 setValue:forKey 。
用 objc_setAssociatedObject 关联以后,用 objc_getAssociatedObject 取出使用。
objc_AssociationPolicy  属性 是设定该value在object内的属性,即 assgin, (retain,nonatomic)...等

3.例:

<pre name="code" class="objc">  

#import <objc/runtime.h>   

  

-(void)testAlertBlock  

{  

    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"this is a bolck_alert"  

                                                  message:@"testtesttest"  

                                                 delegate:self  

                                        cancelButtonTitle:@"取消"  

                                        otherButtonTitles:@"确定", nil nil];  

     

    void (^block)()=^{  

        NSLog(@"alert pressed sure-button");  

    };  

    objc_setAssociatedObject(alert, @"Alert_block", block, OBJC_ASSOCIATION_COPY_NONATOMIC);  

    [alert show];  

}  

  

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  

{  

    void (^block)()=objc_getAssociatedObject(alertView, @"Alert_block");  

    if (block) {  

        block();  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios