问题描述
在 iOS 6 中,viewWillUnload
和 viewDidUnload
已被弃用,UIViewControllers 不再卸载在内存警告期间在屏幕上不可见的视图.视图控制器编程指南 有一个如何手动恢复此行为的示例.
In iOS 6, viewWillUnload
and viewDidUnload
are deprecated and UIViewControllers no longer unload views that are not visible on screen during a memory warning. The View Controller Programming Guide has an example of how to manually restore this behavior.
这是代码示例:
- (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;
}
}
代码示例下方是以下注释:
Below the code sample is the following note:
下次访问视图属性时,重新加载视图和第一次一样.
这里有一个明显的缺陷.如果一个没有加载它的视图的视图控制器收到一个内存警告,它将在 if ([self.view window] == nil)
行加载它的视图,然后继续清理并释放它再次.充其量,这是低效的.最糟糕的是,如果加载了复杂的视图层次结构和支持数据,它会使内存状况变得更糟.我在 iOS 模拟器中验证了这种行为.
There is an obvious flaw here. If a view controller that has not loaded its view receives a memory warning it will load its view in the line if ([self.view window] == nil)
and then proceed to clean up and release it again. At best, this is inefficient. At worst, it makes the memory conditions worse if a complex view hierarchy and supporting data are loaded. I verified this behavior in the iOS simulator.
我当然可以解决这个问题,但 Apple 文档出现这样的错误似乎很奇怪.我错过了什么吗?
I can certainly code around this but seems odd for Apple docs to have such an error. Am I missing something?
推荐答案
在视图控制器中正确检查正在加载和显示在屏幕上的视图是:
The correct check in a view controller for the view being loaded and on screen is:
if ([self isViewLoaded] && [self.view window] == nil)
我在 iOS 6 中使用类似于 iOS 5 的视图控制器卸载视图和清理的完整解决方案如下:
My full solution in iOS 6 to have a view controller unload views and cleanup similar to iOS 5 is the following:
// will not be called in iOS 6, see iOS docs
- (void)viewWillUnload
{
[super viewWillUnload];
[self my_viewWillUnload];
}
// will not be called in iOS 6, see iOS docs
- (void)viewDidUnload
{
[super viewDidUnload];
[self my_viewDidUnload];
}
// in iOS 6, view is no longer unloaded so do it manually
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
if ([self isViewLoaded] && [self.view window] == nil) {
[self my_viewWillUnload];
self.view = nil;
[self my_viewDidUnload];
}
}
- (void)my_viewWillUnload
{
// prepare to unload view
}
- (void)my_viewDidUnload
{
// the view is unloaded, clean up as normal
}
这篇关于在内存警告(Apple 文档缺陷)中卸载 iOS 6 中的视图的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!