UIViewController prevent view from unloading

When my iPhone app receives a memory warning the views of UIViewControllers that are not currently visible get unloaded. In one particular controller unloading the view and the outlets is rather fatal.

I'm looking for a way to prevent this view from being unloaded. I find this behavior rather stupid - I have a cache mechanism, so when a memory warning comes - I unload myself tons of data and I free enough memory, but I definitely need this view untouched.

I see UIViewController has a method unloadViewIfReloadable , which gets called when the memory warning comes. Does anybody know how to tell Cocoa Touch that my view is not reloadable?

Any other suggestions how to prevent my view from being unloaded on memory warning?

Thanks in advance


Apple docs about the view life cycle of a view controller says:

didReceiveMemoryWarning - The default implementation releases the view only if it determines that it is safe to do so

Now ... I override the didReceiveMemoryWarning with an empty function which just calls NSLog to let me know a warning was received. However - the view gets unloaded anyway. Plus, on what criteria exactly is decided whether a view is safe to unload ... oh ! so many questions!


What appears to be working for me was to override setView: to ignore setting to nil. It's kludgy, but then, this is a kludgy issue, and this did the trick:

-(void)setView:(UIView*)view {
    if(view != nil || self.okayToUnloadView) {
        [super setView:view];
    }
}

According to the docs, the default implementation of didReceiveMemoryWarning: releases the view if it is safe to do (ie: superview==nil).

To prevent the view from being released you could override didReceiveMemoryWarning: but in your implementation do not call [super didReceiveMemoryWarning] . That's where the view is released by default (if not visible).

The default didReceiveMemoryWarning releases the view by calling [viewcontroller setView:nil] , so you could override that instead.


Could it be so simple?

Even though nowhere in the documentation this is mentioned, it seems that if I exclusively retain my view in viewDidLoad, then it does not get released on Memory Warning. I tried with several consecutive warnings in the simulator and all still seem good.

So ... the trick for the moment is "retain" in viewDidLoad, and a release in dealloc - this way the viewcontroller is "stuck" with the view until the time it needs to be released.

I'll test some more, and write about the results

链接地址: http://www.djcxy.com/p/58350.html

上一篇: 我滥用UIViewController子类?

下一篇: UIViewController阻止视图卸载