问题描述
对于iOS开发人员,代表几乎无处不在。
For iOS developers, delegates are used almost everywhere.
似乎我们需要使用assign而不是像这样的代理保留
And seems like that we need to use "assign" instead of retain for a delegate like this
@property(assign) id delegate;
原因是避免循环循环问题说:
举个例子, UITableViewController实现UITableViewDelegate协议。 UITableView由它的视图控制器保留,尽管UITableView不保留它的委托。
As an example, let's consider a UITableViewController that implements UITableViewDelegate protocol. UITableView is retained by it's view controller, although the UITableView does not retain it's delegate.
如上面的文档所述,UITableViewController只有完成其所有强引用的释放得到释放由于具有UItableViewController作为委托的UITableView不保留它,所以当UItableViewController的所有者调用释放它时,保留计数将变为零,并且dealloc方法将被调用。
As said on the document above, UITableViewController will only complete its deallocation when all its strong references get released. Since the UITableView that has the UItableViewController as a delegate doesn't retain it, when the owner of UItableViewController calls release on it, the retain count will go to zero and the dealloc method will get called.
现在想象UITableView保留其委托。 UITableViewController的保留计数至少为+2。一个是它的所有者,另一个与UITableView。当UITableViewController的所有者调用释放时,保留计数将转到+1,而不是按预期的方式为零,因此在保留计数达到零之前,dealloc方法将不会被调用。要达到零,UITableViewController将需要释放其UITableView,然后释放其委托(UITableViewController)。因为UITableViewController只会处理它的视图(UITableView),当这个时候的处理将永远不会发生,因为保留计数不会超过+1。
Now imagine that UITableView retains its delegate. UITableViewController will have a retain count of at least +2. One with it's owner and another with UITableView. When UITableViewController's owner calls release on it, the retain count will go to +1, and not to zero as it was expected, and so the dealloc method won't get called until the retain count reaches zero. To reach zero, UITableViewController would need to release its UITableView that would then release its delegate (UITableViewController). Because the UITableViewController will only disposes its view (UITableView) when deallocing this moment would never happen because the retain count won't go bellow +1.
(让我们不要考虑内存警告和任何其他可能的情况...我刚刚看到,ViewController / View不是这个例子的最佳选择,但我已经写得太多了。))
(let's not take in consideration memory warnings and any other possible case...I just saw that ViewController/View is not the best option for this example, but I've written too much already. :))
这是否有意义?
这篇关于属性“分配”和“保留”代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!