402's Dojo

delegate使用方法之assign

很早之前博客园写的文章,避免丢失放在这里。
已经n久没有写博客了,实在是没有时间,只好在麦库上做一些粗略地总结,而不能系统的针对一个问题好好的研究,写在博客中。终于有了一点点时间,先写一点吧。

delegate使用方法:
@property (assign) 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。
啰嗦:
@property (xxx, retain) NSObject * id;(in class1)
在另一个类中引用了上述变量的类中:
class1.id = anObject;(in class2)
这时候anObject就被retain了。
(class1.id ==== [class setId:])

评论