【问题标题】:How to unload view and recreate it using storyboard when didReceiveMemoryWarning在 didReceiveMemoryWarning 时如何使用情节提要卸载视图并重新创建它
【发布时间】:2013-04-04 07:45:39
【问题描述】:

我使用本教程http://www.wannabegeek.com/?p=168 在不同的视图控制器(在我的故事板上)之间滑动。现在我想在收到didReceiveMemoryWarning 时从视图控制器中卸载视图。我试过这个:

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    self.view = nil;
}

当我收到内存警告时,视图显示为黑色。如何从情节提要中恢复视图?

【问题讨论】:

    标签: iphone ios objective-c storyboard


    【解决方案1】:

    请注意,您不必释放视图以响应内存警告。 iOS 6 自动释放后台视图使用的大部分资源。

    如果您选择释放视图,那么只有在它被释放时才应该这样做 目前在屏幕上不可见

    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Add code to clean up any of your own resources that are no longer necessary.
    
        // If view is currently loaded, but not visible:
        if ([self isViewLoaded] && [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.
    
            // Unload the view:
            self.view = nil;
        }
    }
    

    (来自View Controller Programming Guide for iOS 的代码稍作修改以避免加载当前已卸载的视图。)

    使用此代码,如果视图再次可见,则应自动重新加载视图。

    【讨论】:

    • 我已经把它放在我所有的视图控制器 didReceiveMemoryWarning 方法中,但是当我模拟内存警告时,似乎什么也没发生。如果我查看内存,它会下降 0.27MB,然后我得到了 75 个视图控制器......
    • @nonuma:我不知道我能不能帮你。它是否解决了“视图显示黑色”问题? - 您可以向viewDidLoad 添加一个 NSLog 或断点,以验证视图是否实际重新加载(因此之前已卸载)。
    • 我在 viewDidLoad 中放了一个 NSLog,当我模拟内存警告时它不会打印出来,只有“收到内存警告”
    • @nonuma:如果 1) 当前已加载且 2) 当前不可见,则应卸载该视图。 - 如果视图再次可见,则应重新加载视图 (viewDidLoad)。
    • 可能是因为我使用了之前说的教程,所以一开始所有的viewcontrollers都是作为child添加的
    猜你喜欢
    • 2012-10-19
    • 2011-04-28
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多