Associative References

这个也是重量级的api 。
类别里添加属性用到。
根据关联policy 确定是否要释放对象
如果用copy策略obj要实现copy协议

  • (void) setColor:(UIColor *) aColor
    {
    objc_setAssociatedObject(self,&colorKey, aColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

  • (UIColor *) getColor
    {
    return objc_getAssociatedObject(self, &colorKey);
    }
    测试代码:
    m_aClass = [[AClass alloc] init];
    m_aClass.money = @"赵洋";
    tView = [[UIView alloc] init];
    [tView setColor:m_aClass];
    [[tView getColor] setMoney:@"赵洋3"];

    NSLog(@"=:%@",m_aClass.money);
    NSLog(@"=:%@",[tView getColor].money);
    taps:
    The main purpose of this function is to make it easy to return an object to a "pristine state”. You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use objc_setAssociatedObject
    with a nil
    value to clear an association.

你可能感兴趣的:(Associative References)