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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容