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

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

类似于将属性设置成weak引用,我们可以通过自定义容器类和关联策略来实现这种弱引用行为。以下是详细的步骤说明和优化后的内容:

首先,我们创建一个自定义容器类WeakAssociationObjectContainer,它需要拥有一个弱引用对象。声明如下:

@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

这种方法通过关联策略OBJC_ASSOCIATION_RETAIN_NONATOMIC来实现,其可行性最终取决于真实对象的归 Eagles情况。这种手动管理方式提供了类似weak属性的行为,但需要特别注意对象生命周期和内存管理问题。通过这种方式,可以在不支持weak属性的iostream中实现对属性对象的弱引用。

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

你可能感兴趣的文章
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.environ 没有设置环境变量
查看>>