iphone - 当内存警告不足时,通过界面构建​​器添加的 View 会发生什么情况?

标签 iphone ios objective-c memory-management

当我们收到低内存警告时,我们释放所有 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 会像第一次一样重新加载。从象形上讲,它非常有意义 -

enter image description here

[source]

关于iphone - 当内存警告不足时,通过界面构建​​器添加的 View 会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587654/

相关文章:

iphone - UISegmentedControl 选定索引始终为 0?

iphone - UILabel 重新缩放和光栅化时的图像质量问题

ios - 将 NSTimer 的 fireDate 之前的时间加倍

ios - 添加新行时 UITableView 停止滚动

ios - 我怎样才能只要求使用 Alamofire 进行一次身份验证?

ios - KVO 不适用于类别

ios - UICollectionView 图片加载问题

ios - NSBundle pathForResource : returns nil

iphone - 在 C++ 中编码/解码 NSCoder 数据

iphone - 应用程序 "failed to resume in time"并挂起