delegate使用方法之assign

本文解释了在Objective-C中为何在定义delegate时应使用assign而非retain属性。通过避免循环引用(retain loop)确保内存管理正确,并提供了详细的场景说明。

delegate使用方法:

@property (assign) <id>xxxDelegate delegate;

正确的使用方法是使用assign属性而不是retain。援引stackoverflow查到的东西:

"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."

这段话比较好懂,assign属性直接给实例变量赋值,而不是将引用计数加一。最适合于原始类型如:int,float,和一些你不直接拥有的对象,如:delegates。

之所以对于delegate这类对象使用assign而不是用retain是为了防止循环retain(retain loop),retain delegate会引起循环retain是因为:

A creates B A sets itself as B's delegate. A is released by its owner. If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.(这段话反复理解一下,刚开始我也没看懂。)

上面介绍了为什么使用assign而不是retain定义一个delegate,其原因是为了避免retain loop,再说下retain loop是怎么回事:

Retaining an object creates a strong reference(强引用), and an object cannot be deallocated until all of its strong references are released. If two objects retain each other, neither object ever gets deallocated because the connection between them cannot be broken。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值