博客
关于我
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 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的 SSL 模块安装
查看>>
Nginx 的优化思路,并解析网站防盗链
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
nginx 禁止以ip形式访问服务器
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置服务器文件上传与下载
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
Nginx 集成Zipkin服务链路追踪
查看>>
nginx 集群配置方式 静态文件处理
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>