It seems to me that memory usage is one of the major things you need to be careful of when iPhone programming. The common pattern is to create your subviews, labels, etc in viewWillLoad and set them to nil in viewWillUnload. I understand the reasoning behind this.
But why not set everything (except things that took a long time to construct) to nil in viewWillDisappear instead of viewWillUnload?
When your view disappears, you don't really need to allocate memory to the UI items anymore. When your view appears again, you can then create the UI items again.
I know you can do what I just described... I know it's entirely possible, but my question is why isn't THIS the common pattern?
Is there a hidden major cost to allocating new memory? Will it cause strange behavior? Is it simp开发者_C百科ly unnecessary?
- Common pattern is actually
viewDidLoad
andviewDidUnload
- A good reason for this pattern is performance. The will appear and disappear methods are often called when a UINavigationController is used and just because a view will disappear it does not mean that it will not appear again shortly. So if thats the case why unload everything if memory is not an issue and have to recreate user state each time (fetch data, set switches, segmented controls, etc). While memory is important on a device so is performance, no one wants to use a "laggy" UI. Proper use of
-(void)viewDidLoad
,-(void)viewDidUnload
, and- (void)didReceiveMemoryWarning
will allow you to maximize memory and performance.
Well if you are just displaying a modelviewcontroller then the view behind it will unload, which will make coming back that view slow. That is what the viewDidLoad
and viewDidUnload
are used for not the viewWillAppear
and viewWillDisappear
(or viewDidDisappear
) .
Allocating object is slow, so you should only do it when needed.
The viewDidLoad
and viewDidUnload
are automatically called for view that are no longer visible and the system needs more memory.
This happens for example when the applicationDidReceiveMemoryWarning is called by the system, then UINavigationController will unload all view in the stack, but not the viewControllers. This make it easy to return to any state the view was in when it got unloaded.
精彩评论