ARC委托内存管理 [英] ARC delegate memory management
问题描述
在Apple的文档中,它说
In Apple's docs it says
如果您需要管理除释放实例变量之外的资源,则可以实现dealloc方法。您不必(实际上不能)释放实例变量,但您可能需要在系统类和其他未使用ARC编译的代码中调用[systemClassInstance setDelegate:nil]。
You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC.
这是否包括UIKit和Framework委托,例如, UIPageViewController
的父代有委托 UIPageViewControllerDelegate
- 这必须在dealloc中填充吗?
Does this include UIKit and Framework delegates, for example, the parent of a UIPageViewController
has the delegate UIPageViewControllerDelegate
- does this have to be nilled in the dealloc?
推荐答案
当你有一个关系在父控制器及其视图之间,父控制器作为视图委托,其中一个关系不能保留另一个,否则将有一个保留周期和内存泄漏。
When you have a relationship between the a parent controller and its view, where the parent controller acts as the views delegate, one of those relationships must not retain the other, otherwise you will have a retain cycle and a memory leak.
有两种方法可以执行此操作:
-
首先是将委托标记为__unsafe_unretained。如果这样做,您将需要在控制器的dealloc中手动删除引用。
There first is to mark the delegate as __unsafe_unretained. If you do this you will need to manually nil out the reference in the dealloc of the controller.
第二个是使用弱引用。大多数ARC发生在编译时。这有助于通过减少垃圾收集器会发生的CPU周期来节省电池消耗。然而,对于弱引用,有一个运行时过程来维护这些变量的映射,观察它们,并根据需要对它们进行排序。这就是为什么弱引用需要iOS5.1 - 它不仅仅是一个编译器功能。
The second is to use a weak reference. Most of ARC happens at compile time. This helps to save battery drain by reducing the CPU cycles that would otherwise occur with a garbage collector. However, for weak references, there's a run-time process that maintains a map of these variables, observes them, and nils them out as required. This is why weak references required iOS5.1 - its not just a compiler feature.
如果使用太多的弱引用,它可能是一个性能开销。在实践中,这几乎不会成为一个问题。
If you use too many weak references, it can be a performance overhead. In practice this will hardly ever be a concern.
摘要
- 如果使用弱引用,则不需要手动将其删除。检查你没有内存,通过一个强有力的引用的保留周期。
- 如果你真的必须使用__unsafe_unretained(也就是'assign')。
- 同样的规则适用于UIKit和框架类。好的是,它们非常一致。
更新
纠正我的诡计评论:如果您的代表在控制器执行之前移除,那么您将需要手动将其关闭控制器 - 谢谢@borrden。
- Correcting my dodgy comment: If your delegate goes away before the controller does, then you will need to nil it off the controller manually - thanks @borrden.
这篇关于ARC委托内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!