博客
关于我
association weak 属性
阅读量:585 次
发布时间:2019-03-11

本文共 1793 字,大约阅读时间需要 5 分钟。

association weak 属性

当给类添加分类添加属性时,我们一般使用关联对象来实现

管理关联对象的方法:

objc_setAssociatedObject(id object, void * key, id value, <objc_AssociationPolicy policy)
以给定的key为对象设置关联对象的value

objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)

根据key从对象中获取相应的关联对象的value

objc_removeAssociatedObjects(id _Nonnull object)

移除所有关联对象

但是查看runtime.h中的objc association提供的objc_AssociationPolicy(如下),我们可以看到没有提供真正的weak属性,

关联类型 等效的属性
OBJC_ASSOCIATION_ASSIGN @property(assign)/@property(unsafe_unretained)
OBJC_ASSOCIATION_RETAIN_NONATOMIC @property(strong,nonatomic)/retain
OBJC_ASSOCIATION_COPY_NONATOMIC @property(copy,nonatomic)
OBJC_ASSOCIATION_RETAIN @property(strong,atomic)/retain
OBJC_ASSOCIATION_COPY @property(copy,atomic)

strong + WeakAssociationContainer 的方式,实现对属性对象的 weak 引用。

思路是:

  • 声明一个 WeakAssociationContainer 类对真实的属性对象进行 weak 属性引用
  • 添加属性时,关联对象使用 OBJC_ASSOCIATION_RETAIN_NONATOMIC策略,对 WeakAssociationContainer 进行 retain association
  • 这样在 get 关联属性对象时由于 WeakAssociationContainer 对真是属性对象的 weak 引用,会返回 nil 而不是野指针
@interface WeakAssociationObjectContainer : NSObject@property (nonatomic, readonly, weak) id weakObject;- (instancetype)initWeakObject:(id)object;@end@implementation WeakAssociationObjectContainer- (instancetype)initWeakObject:(id)object {    self = [super init];    if (self) {        _weakObject = object;    }        return self;}@end    @implementation NSObject (WeakAssociate)- (void)setweakProperty:(id)weakProperty {    WeakAssociationObjectContainer *container = [[WeakAssociationObjectContainer alloc] initWeakObject:weakProperty];    objc_setAssociatedObject(self, @selector(weakProperty), container, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}- (id)weakProperty {    WeakAssociationObjectContainer *container = objc_getAssociatedObject(self, _cmd);    return container.weakObject;}@end

转载地址:http://wlttz.baihongyu.com/

你可能感兴趣的文章
Nginx安装及配置详解
查看>>
Nginx实战经验分享:从小白到专家的成长历程!
查看>>
Nginx实现反向代理负载均衡
查看>>
nginx实现负载均衡
查看>>
nginx开机启动脚本
查看>>
nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
查看>>
nginx总结及使用Docker创建nginx教程
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>
nginx最最最详细教程来了
查看>>
Nginx服务器---正向代理
查看>>
Nginx服务器上安装SSL证书
查看>>
Nginx服务器的安装
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>
nginx添加模块与https支持
查看>>
Nginx用户认证
查看>>
Nginx的location匹配规则的关键问题详解
查看>>