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

你可能感兴趣的文章
Node.js安装和入门 - 2行代码让你能够启动一个Server
查看>>
node.js安装方法
查看>>
Node.js官网无法正常访问时安装NodeJS的方法
查看>>
node.js模块、包
查看>>
node.js模拟qq漂流瓶
查看>>
node.js的express框架用法(一)
查看>>
Node.js的交互式解释器(REPL)
查看>>
Node.js的循环与异步问题
查看>>
Node.js高级编程:用Javascript构建可伸缩应用(1)1.1 介绍和安装-安装Node
查看>>
nodejs + socket.io 同时使用http 和 https
查看>>
NodeJS @kubernetes/client-node连接到kubernetes集群的方法
查看>>
NodeJS API简介
查看>>
Nodejs express 获取url参数,post参数的三种方式
查看>>
nodejs http小爬虫
查看>>
nodejs libararies
查看>>
vue3+element-plus 项目中 el-switch 刷新后自动触发change?坑就藏在这里!
查看>>
nodejs npm常用命令
查看>>
nodejs npm常用命令
查看>>
Nodejs process.nextTick() 使用详解
查看>>
NodeJS yarn 或 npm如何切换淘宝或国外镜像源
查看>>