delegate使用方法之assign

来源:互联网 发布:php解析json数组对象 编辑:程序博客网 时间:2024/06/05 04:58

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。

0 0