且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么使用弱指针进行委托?

更新时间:2023-11-13 23:46:40

对象弱保留其委托的原因是为了避免保留循环.想象以下场景:对象 a 创建 b 并保留它,然后将自己设置为 b 的委托.a 由其所有者释放,留下一个包含 ab 的保留循环.这实际上是一个非常常见的场景.考虑一个视图控制器,它拥有一个视图并充当该视图的委托.在这种情况下,视图不应该保留控制器——作为适当的 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.