xcode 是否保留了代表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13972259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:22:19  来源:igfitidea点击:

Is a delegate retained?

objective-ciosxcode

提问by Kalpesh

I know , the delegate is never retained! Ever!

我知道,委托永远不会被保留!曾经!

But can anyone explain me why delegate is never retained ?...

但是谁能解释我为什么永远不会保留委托?...

Thanx in advance

提前谢谢

回答by Tom van der Woerdt

It's a memory management thing.

这是一个内存管理的东西。

Objective-C works with reference counts to keep the memory clean. This does mean that it can't detect cyclic relationships.

Objective-C 使用引用计数来保持内存干净。这确实意味着它无法检测循环关系。

Example:

例子:

  • Object A owns object B. Object B is retained by object A.
  • Object B has a delegate that is object A. Object A is retained by object B.
  • Object C owns object A. Object A is retained by object C.
  • Object A now has a retainCount of 2, and object B has a retainCount of 1
  • Object C gets freed, and releases object A
  • Object A and B now have a retainCount of 1, because they own eachother. The system will not free them, because the retainCount is still 1 (still owned by another object)
  • Memory leak!
  • 对象 A 拥有对象 B。对象 B 由对象 A 保留。
  • 对象 B 有一个委托,即对象 A。对象 A 由对象 B 保留。
  • 对象 C 拥有对象 A。对象 A 由对象 C 保留。
  • 对象 A 现在的保留计数为 2,对象 B 的保留计数为 1
  • 对象 C 被释放,并释放对象 A
  • 对象 A 和 B 现在的 retainCount 为 1,因为它们彼此拥有。系统不会释放它们,因为 retainCount 仍然是 1(仍然由另一个对象拥有)
  • 内存泄漏!

回答by djromero

It's up to you. If you declare it to be retained (strongin ARC) it'll be retained.

由你决定。如果您声明它被保留(strong在 ARC 中),它将被保留。

The rule is to not retain it because it's already retained elsewhere and more important you'll avoid retain cycles.

规则是不要保留它,因为它已经在别处保留了,更重要的是您将避免保留循环

回答by Ismael

To expand on djromero's answer:

扩展 djromero 的回答:

If you have a UIViewControllerwhich contains a UITableView, the controller will be most likely retaining the table and it will be it's delegate / dataSource. If the table retains the delegate / dataSource, then they will be retaining each other and thus never getting released.

如果您有一个UIViewController包含 a UITableView,则控制器很可能会保留该表,并且它将是它的委托/数据源。如果表保留了委托/数据源,那么它们将相互保留,因此永远不会被释放。

回答by Trausti Thor

The whole idea is that the delegate should always outlive the object that assigns it as a delegate. So the webview will be released before the delegate that is assigned.

整个想法是委托应始终比将其分配为委托的对象存活时间更长。因此 webview 将在分配的委托之前发布。