gpt4 book ai didi

uiviewcontroller - 在内存警告(Apple 文档缺陷)中卸载 iOS 6 中的 View 的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-04 01:52:08 26 4
gpt4 key购买 nike

在 iOS 6 中,viewWillUnloadviewDidUnload已弃用,并且 UIViewControllers 不再卸载在内存警告期间在屏幕上不可见的 View 。 View Controller Programming Guide有一个如何手动恢复此行为的示例。

这是代码示例:

- (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;
}
}

代码示例下方是以下注释:

The next time the view property is accessed, the view is reloaded exactly as it was the first time.



这里有一个明显的缺陷。如果尚未加载其 View 的 View Controller 收到内存警告,它将在行 if ([self.view window] == nil) 中加载其 View 。然后继续清理并再次释放它。充其量,这是低效的。最糟糕的是,如果加载了复杂的 View 层次结构和支持数据,它会使内存状况变得更糟。我在 iOS 模拟器中验证了这种行为。

我当然可以解决这个问题,但 Apple 文档出现这样的错误似乎很奇怪。我错过了什么吗?

最佳答案

在 View Controller 中正确检查正在加载和显示在屏幕上的 View 是:
if ([self isViewLoaded] && [self.view window] == nil)
我在 iOS 6 中有一个 View Controller 卸载 View 和清理类似于 iOS 5 的完整解决方案如下:

// 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
}

关于uiviewcontroller - 在内存警告(Apple 文档缺陷)中卸载 iOS 6 中的 View 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12541216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com