我在读一本书,它建议将我的 IBOutlets
声明为 weak
应该可以解决当我的应用程序收到内存不足警告时的问题。例如,我现在不再需要在 viewDidUnload
方法中将这些 socket 设置为 nil。
我还听说在 iOS6 中 viewDidUnload
被弃用,取而代之的是 didReceiveMemoryWarning
被调用。
无论如何,我该如何继续,我是否应该将我的 IBOutlet
声明为 weak
,并“忘记”实现 didReceiveMemoryWarnings
和 viewDidUnloads
?
最佳答案
不是所有的 IBOutlets
都应该是 weak
。来自Apple docs (Resource Programming guide)的推荐
Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak, because:
Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.
The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).
例子:
XIB 中的顶级对象应声明为strong
,任何其他 subview /控件应为weak
属性。
@property (nonatomic, weak) IBOutlet MyView *viewContainerSubview; @property (nonatomic, strong) IBOutlet MyOtherClass *topLevelObj;
使用 ARC weak
生命周期限定符有其自身的优势(Refer Apple docs)因为,
__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
因此您不必担心设置 IBOutlets
nil
,它的生命周期自动受其顶级实例的约束。
didReceiveMemoryWarning
以清除任何占用内存的可重新创建资源。当您收到 didReceiveMemoryWarning
调用时,它应该用于释放使用的非关键资源,例如:自定义数据结构、用于填充 UI 的网络服务响应等。任何资源需求的非关键性由开发者决定。
关于ios - didReceiveMemoryWarning,viewDidUnload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18378866/