当我们收到低内存警告时,我们释放所有 View ,将 outlets 设置为 nil,然后重新创建它们。 但对于在界面构建器中添加的 View ,它们仅在我们调用 initWithNibName 时添加。
因此,通过界面构建器使用大量 View 通常是不好的做法,还是由 didReceiveMemoryWarning(iOS 6+) 或 viewDidUnload 的原始
?UIViewController
实现自动处理(iOS 5 及以下版本)
最佳答案
viewcontroller
的默认行为是在第一次访问 View 属性时加载其 View 层次结构,然后将其保存在内存中,直到 View Controller 被释放。没有迹象表明使用代码创建的 View 与在 Interface Builder 中创建的 View 不同。由于应用程序维护,我个人更喜欢 InterfaceBuilder,因为 UI 代码变得非常复杂,并且将 UI 元素与 UI 元素的功能方面分开是一个干净的 fork ,使新程序员可以轻松维护您的代码库。
但是当谈到释放内存时,didReceiveMemoryWarning
委托(delegate)将用于显式释放 View 层次结构,如果您的应用程序需要额外的内存。
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Add code to clean up any of your own resources that are no longer necessary.
if ([self.view window] == nil)
{
// Add code to preserve data stored in the views that might be
// needed later.
// Add code to clean up other strong references to the view in
// the view hierarchy.
self.view = nil;
}
return;
}
注意这里我们测试 View Controller 的 View 是否不在屏幕上。如果 View 与窗口相关联,那么它会清除 View Controller 对 View 及其 subview 的任何强引用。如果 View 存储需要重新创建的数据,则此方法的实现应在释放对这些 View 的任何引用之前保存该数据。通过存储,您可以将其作为先前 View Controller 内存的一部分保存在内存中,或者将其存储在 coredate 或其他一些持久性(磁盘缓存等)方式中。
下次访问 View 属性时, View 会像第一次一样重新加载。从象形上讲,它非常有意义 -
关于iphone - 当内存警告不足时,通过界面构建器添加的 View 会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587654/