博客
关于我
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/

你可能感兴趣的文章
NFS网络文件系统
查看>>
NFS远程目录挂载
查看>>
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
NFV商用可行新华三vBRAS方案实践验证
查看>>
ng build --aot --prod生成文件报错
查看>>
ng 指令的自定义、使用
查看>>
nghttp3使用指南
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>