关联对象

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 void *key, id value, objc_AssociationPolicy policy)

id objc_getAssociatedObject(id object, const void *key)

void objc_removeAssociatedObjects(id object)




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];
   
    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();
    }
}


 
 

上面例子中,把block关联到 alert里面



4.注意retain circle问题,关联block时要注意内存管理,防止retain circle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值