为什么使用弱指针进行委派? [英] Why use weak pointer for delegation?
问题描述
我不明白为什么用弱指针定义委托是正确的:
I can't understand why it is correct to define a delegate with weak pointer :
@property (nonatomic,weak) id delegate;
我不明白为什么不必保留对委托的引用...我不希望释放用作委托的对象...因此,我宁愿使用强参考不是弱项!
I can't realize why isn't necessary to retain a reference to the delegate... i don't want the object that i use as the delegate to be deallocated... thus, i would prefer using a strong reference not a weak!
在很多情况下,委托是将要创建我的类实例的对象,在这种情况下,创建弱引用将是避免保留周期的好方法……但是如果我选择一个完全不同的对象怎么办?作为代表?
In many cases the delegate is the same object where the instance of my class will be created, in this case creating a weak reference would be a great solution to avoid retain cycle... but what if I choose a totally different object as the delegate ?
我搜索了有关堆栈溢出的其他问题,但找不到能帮助我完全理解这种情况的东西.
I searched for other questions on stack overflow but I can't find something that can help me to fully understand this situation.
推荐答案
对象弱地保留其委托的原因是为了避免保留周期.想象以下情况:对象a
创建b
并保留它,然后将其自身设置为b
的委托. a
由其所有者释放,保留一个包含a
和b
的保留周期.这实际上是一个非常常见的情况.考虑一个拥有一个视图并充当该视图的委托的视图控制器.在这种情况下,视图不应保留控制器,这是适当的MVC架构的主要内容,并应防止保留周期.
The reason that objects weakly retain their delegates is to avoid retain cycles. Imagine the following scenario: object a
creates b
and retains it, then sets itself as b
's delegate. a
is released by its owner, leaving a retain cycle containing a
and b
. This is actually a very common scenario. Consider a view controller that owns a view and acts as that view's delegate. In this case, the view should not retain the controller—as a mater of proper MVC architecture and to prevent retain cycles.
这篇关于为什么使用弱指针进行委派?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!