ios - 代理的属性 "assign"和 "retain"

标签 ios delegates properties retain assign

对于 iOS 开发者来说,委托(delegate)几乎无处不在。

而且看起来我们需要使用“分配”而不是像这样的委托(delegate)保留

@property(assign) id delegate;

原因是为了避免循环问题Why are Objective-C delegates usually given the property assign instead of retain?

看了很多代码,他们还在用“retain”。所以这里的问题是,如果我们对委托(delegate)使用保留,我们还会遇到循环问题吗?

谢谢

最佳答案

documentation说:

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

例如,让我们考虑一个实现了 UITableViewDelegate 协议(protocol)的 UITableViewController。 UITableView 由它的 View Controller 保留,尽管 UITableView 不保留它的委托(delegate)。

如上文所述,UITableViewController 只有在其所有强引用都已释放后才会完成释放。由于将 UItableViewController 作为委托(delegate)的 UITableView 不会保留它,因此当 UItableViewController 的所有者对其调用 release 时,保留计数将变为零,并且将调用 dealloc 方法。

现在假设 UITableView 保留了它的委托(delegate)。 UITableViewController 的保留计数至少为 +2。一个是它的所有者,另一个是 UITableView。当 UITableViewController 的所有者对其调用 release 时,保留计数将变为 +1,而不是预期的零,因此在保留计数达到零之前不会调用 dealloc 方法。要达到零,UITableViewController 需要释放其 UITableView,然后释放其委托(delegate) (UITableViewController)。因为 UITableViewController 只会在解除分配时释放它的 View (UITableView),这一刻永远不会发生,因为保留计数不会低于 +1。

(让我们不考虑内存警告和任何其他可能的情况......我只是看到 ViewController/View 不是这个例子的最佳选择,但我已经写了太多了。:))

这有意义吗?

关于ios - 代理的属性 "assign"和 "retain",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5176261/

相关文章:

ios - AppDelegate valueForUndefinedKey

performance - 究竟什么是委托(delegate)?

python - 属性 setter 在 Python 类中不起作用

java - Netbeans - .properties 文件默认编码 |奇怪的行为

ios - 如何在 iOS 中进行简单的 AB 测试

vb.net - 委托(delegate)如何解决跨线程问题?

ios - 如何将单元格添加到 UICollectionview 中的 UITableview

javascript - 未选中返回盒子上的属性(property)

ios - 长按时如何检测 selectedSegmentIndex ?

ios - 在CGAffineTransform xcode中获取比例值和旋转值