为什么使用弱指针进行委托? [英] Why use weak pointer for delegation?

查看:352
本文介绍了为什么使用弱指针进行委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么用弱指针定义一个委托是正确的:

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 由其所有者释放,留下一个包含 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.

这篇关于为什么使用弱指针进行委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆