博客
关于我
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 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>
Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)
查看>>
Nginx代理初探
查看>>
nginx代理地图服务--离线部署地图服务(地图数据篇.4)
查看>>
Nginx代理外网映射
查看>>
Nginx代理模式下 log-format 获取客户端真实IP
查看>>
Nginx代理解决跨域问题(导致图片只能预览不能下载)
查看>>
Nginx代理配置详解
查看>>
Nginx代理静态资源(gis瓦片图片)实现非固定ip的url适配网络环境映射ip下的资源请求解决方案
查看>>