Why is viewDidUnload called less often than viewDidLoad? - iphone

I put NSLog(#"%#::%#", [[self class] description], NSStringFromSelector(_cmd)); in both viewDidLoad and viewDidUnload of a view controller.
In the log, I found viewDidLoad is called a lot more than viewDidUnload when the app moves to and from different .nibs.
Why?

The viewDidLoad and viewDidUnload is not corresponding to each other.
The viewDidUnload will only be called when you receive a memory warning. The system then will automatically call your viewDidUnload.
In the normal case, when you push a MyViewController and pop it out. The life cycle will happens like this:
init
viewDidLoad
release
That means, whenever you init and push/present a view, a viewDidLoad will be called. But when you pop the view, the release will be called in normal case and viewDidUnload will be called in memory warning case.
This is quite implicit and Apple doesn't state it clearly on the Guide. Here is some reference: Load and Unload cycle

I imagine that in the cases where -viewDidUnload wasn't called, the view controller was released.
viewDidLoad: controller loads view
viewDidUnload: memory warning, controller unloads view
viewDidLoad: controller loads view again
-: controller gets released, doesn't explicitly unload the view
You and up with 2 -viewDidLoad calls and 1 `-viewDidUnload' call.
Maybe also put a NSLog into the -dealloc method and see if the number of -dealloc and -viewDidUnload calls combined matches the number of -viewDidLoad calls.

when a new view loads, the old view can still be loaded in the background.
you are searching for viewWillAppear as conterpart i think.
views only unload in case of a memorywarning.

Related

poptorootviewcontroller not calling dealloc methods and viewdidappear method of rootview controller in a sequence

I have a navigation controller with 4 VCs pushed into it. I have a singleton class with a delegate property that is set to the VC which is on top of the stack. I am setting this delegate to nil in the dealloc method of each VC. I am setting the delegate in the viewdidappear method of the rootVC.
When I pop back to root VC from the 4th VC, the sequence of calling the dealloc methods (of all the VCs in stack) and viewdidappear method is following:
"FirstVC dealloc called"
"SecondVC dealloc called"
"viewdidappear of root VC is called"
"ThirdVC dealloc called"
Now, the issue I am facing is that the delegate gets set to nil even though I am setting it to self in the root VC's viewdidappear method (which is visible from the control flow too). How can I prevent this situation? I want the viewdidappear method to get called once all the VCs are really deallocated.
Thanks,
Obaid
Since you can't predict the order of method calls unless Apple publishes some guarantee of what they are, perhaps you could program the singleton to be defensive by creating a method such as:
- (void)removeDelegate:(UIViewController *)oldDelegate;
If the delegate matches the specified old delegate, set it to nil.
dealloc is called automatically once a object is no longer needed. When you pop the ThirdVC, since the delegate property is still retaining it, dealloc doesn't get called. Then, when your rootVC's viewDidAppear gets called, it sets the rootVC as the delegate. At this momment, your thirdVC is no longer needed, which triggers the dealloc.
One thing you could do is set the delegate property to nil not on dealloc, but on the viewWillDisappear method of each ViewController, since this method will surely get called before the next ViewController appears.

Correctly Allocating / Deallocating UINavigationControllerDelagate

I have a UIViewController that needs to make use of the UINavigationControllerDelegate, specifically the willShowViewController method.
I am setting <UINavigationControllerDelegate> in my implementation, then I am setting the delegate to self in viewDidLoad (self.navigationController.delegate = self;). Then I implement the willShowViewController method and it works fine, however when the view controller is popped off the stack, there is a memory leak and my app is crashing. I've tried doing self.navigationController.delegate = nil; in both viewDidUnload and dealloc but it doesn't help matters.
What is the correct way I can implement this delegate for use in just one of my viewcontrollers?
viewDidUnload will not necessarily ever be called (it's mostly for handling low memory conditions) and by the time dealloc is called, the view controller is probably no longer contained in the navigation controller, so self.navigationController would be nil.
I'd suggest setting the delegate to nil in your viewWillDisappear: implementation (and setting it in viewWillAppear: instead of viewDidLoad).
Btw, you're seeing the exact opposite of a memory leak here. A memory leak would be memory that cannot be reached anymore and will never be freed. Here you have memory that has already been freed (your view controller), but is still referenced by a (dangling) pointer, leading to the crash. A real leak would usually not result directly in a crash.
You should either keep a weak (non-retaining) reference to the navigation controller or reset its delegate when it becomes clear the navigation controller is going to pop your controller. The truth is, in dealloc self.navigationController is already nil, and viewDidUnload is not sent when your controller gets popped.
you should setting the delegate is self in your [viewDidAppear:] implementation and setting the delegate is nil in your [viewWillDisappear:] implementation.
Tips: you shouldn't set the delegate is nil in dealloc implementation, because when the dealloc is called, the viewController is popped from the navigationcontroller stack so self.navigationController must be nil.

Would a UIViewController currently in UINavigationContoller's viewController stack be unloaded?

Also would anybody tell me what's the difference between viewDidUnload and dealloc?
viewDidUnload : called during low-memory conditions when the view controller needs to release its view and any objects associated with that view to free up memory. More
dealloc: Deallocates the memory occupied by the receiver, An object’s dealloc method is invoked indirectly through the release NSObject protocol method. More
Yes, it could be unloaded if a memory warning occurs.
As for the difference between viewDidUnload and dealloc - the former is called when your view is unloaded, typically because of a low memory situation. The latter is called when your object's retain count reaches zero (i.e. it is completely released from memory)
UIViewControllers are never unloaded. The UIViews they own can be.
So, if you question is if a UIView can be unloaded although its controller has been pushed on to the navigation controller, the answer is yes. Only the currently displayed UIView will not be unloaded (if you don't prevent the unloading mechanism from working).
Furthermore, viewDidUnload is a message that is sent to a UIViewController when the view it manages has been unloaded, which usually is not the same as deallocating the view. In fact, when a view is actually deallocated, it is unloaded for sure, but viewDidUnload is not sent.
A UIViewController that has been pushed onto a nav controller stack, and hasn't yet been popped, will not be dealloc'd. However, its view property may be unloaded -- in particular, if a low memory condition occurs AND the view for that view controller isn't currently visible (something is covering it, like a modal dialog, or another VC pushed on top of it), the view may be unloaded by the system.
viewDidUnload is a bad name for what the method does. It is called when a low memory condition caused the view to be unloaded -- i.e. it is not the 'opposite' method to viewDidLoad, which I think you might reasonably expect.
More info:
When should I release objects in -(void)viewDidUnload rather than in -dealloc?
Also important is that viewDidLoad will be called again after viewDidUnload. If you perform setup in viewDidLoad, you should deal with it in such a way that a second call to it will not cause memory leaks.
Either tear everything down in viewDidUnload (polite, if they are memory intensive), or check for their existence when you set them up and don't do it twice. (And, of course, totally tear them down before or during the dealloc method.)
You are not guaranteed that viewDidUnload will be invoked before dealloc is.

What exactly must I do in viewDidUnload?

I tend to release my stuff in -dealloc, and now iPhone OS 3.0 introduced this funny -viewDidUnload method, where they say:
// Release any retained subviews of
the main view. // e.g. self.myOutlet
= nil;
So -viewDidUnload seems to get called when the view of the view controller has been kicked off from memory. And if I have subviews attached to the main view of the view controller, I have to release that stuff only HERE, but not in -dealloc as well?
That's confusing. Also, what if -dealloc causes the view to be unloaded (released)? Then again, it will call -viewDidUnload?
I do realize the difference, that -viewDidUnload is just for the case where the view itself gets killed, but the view controller stays in memory. And -dealloc is for the case where the whole thing goes to trash.
Maybe someone can clear up the confusion.
The intent here is to "balance out" your subview management. Anything that you create in viewDidLoad should be released in viewDidUnload. This makes it easier to keep track of what should be released where. In most cases, your dealloc method is a mirror-image of your init method, and your viewDidUnload will be a mirror image of your viewDidLoad method.
As you pointed out, the viewDid... methods are to be used when the view itself is loaded and unloaded. This permits a usage pattern in which the view controller remains loaded in memory, but the view itself can be loaded and unloaded as required:
init
viewDidLoad
viewDidUnload
viewDidLoad
viewDidUnload
...
dealloc
Of course, it doesn't hurt to release things in your dealloc method as well, as long as you set them to nil when you release them in viewDidUnload.
The following quote from the Memory Management section of Apple's UIViewController documentation, describes it in more detail:
...in iPhone OS 3.0 and later, the viewDidUnload method may be a more appropriate place for most needs.
When a low-memory warning occurs, the UIViewController class purges its views if it knows it can reload or recreate them again later. If this happens, it also calls the viewDidUnload method to give your code a chance to relinquish ownership of any objects that are associated with your view hierarchy, including objects loaded with the nib file, objects created in your viewDidLoad method, and objects created lazily at runtime and added to the view hierarchy. Typically, if your view controller contains outlets (properties or raw variables that contain the IBOutlet keyword), you should use the viewDidUnload method to relinquish ownership of those outlets or any other view-related data that you no longer need.
As you say viewDidUnload will be called if self.view=nil, this generally occurs if you get memory warning. In this method you must release any subview of the mainview which can easily be created by .xib or loadView method. You should release any data object if you create them in viewDidload or loadView etc. because these methods will be called again to present view to the user, those data can be recreated easily.
When you get a memory warning usually the viewcontroller will unload it's view but itself will not be dealloc.
All that can be re-created easily should be unloaded, but not the model of the view.

When should I release objects in -(void)viewDidUnload rather than in -dealloc?

What is the -(void)viewDidUnload is good for?
Could I not just relase everything in -dealloc? If the view did unload, wouldn't -dealloc be called anyway?
In addition to what has already been indicated, I wanted to elaborate more about logic behind -viewDidUnload.
One of the most important reasons for implementing it is that UIViewController subclasses commonly also contain owning references to various subviews in the view hierarchy. These properties could have been set through IBOutlets when loading from a nib, or programmatically inside -loadView, for instance.
The additional ownership of subviews by the UIViewController means that even when its view is removed from the view hierarchy and released to save memory, through which the subviews are also released by the view, they will not actually be deallocated because the UIViewController itself still contains its own outstanding retaining references to those objects as well. Releasing the UIViewController additional ownership of these objects ensures they will be deallocated as well to free memory.
The objects that you release here are usually recreated and set again when the UIViewController view is re-loaded, either from a Nib or through an implementation of -loadView.
Also note that the UIViewController view property is nil by the time this method is called.
As the documentation says:
It is called during low-memory conditions when the view controller needs to release its view and any objects associated with that view to free up memory.
In the same situation dealloc is not called. This method is only available in OS3 and above. Dealing with the same situation in iPhone OS 2.x was a real pain!
Update July 2015: It should be noted that viewDidUnload was deprecated in iOS 6 because "Views are no longer purged under low-memory conditions and so this method is never called." So, the modern advice is not to worry about it and use dealloc.
This is because you will typically set the #property as "(nonatomic, retain)" and as such the setter that is created for you releases the current object and then retains the argument i.e.
self.property = nil;
...does something along the lines of:
[property release];
property = [nil retain];
Therefore you are killing two birds with one stone: memory management (releasing the existing object) and assigning the pointer to nil (since sending any message to a nil pointer will return nil).
Hope that helps.
Remember that viewDidUnload is a method in the view controller, not in the view. The view's dealloc method will get called when the view unloads, but the view controller's dealloc method may not be called until later.
If you get a low memory warning and your view isn't showing, which will happen for instance about any time you use a UIImagePickerController to let the user take a picture, your view will get unloaded and will need to get reloaded after that.
Conclusion:
View Controllers have a view property. Typically a nib or piece of code adds other views to this view. This happens often inside a -viewDidLoad method, like this:
- (void)viewDidLoad {
[super viewDidLoad];
[self createManyViewsAndAddThemToSelfDotView];
}
in addition, a nib file may create a button and append it to the view controller's view.
On iPhone OS 2.2, when -didReceiveMemoryWarning was invoked from the system, you had to release something to free up memory. You could release the whole view controller's view if that made sense. Or just big memory-consuming contents in it.
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
Now, in the new OS 3.0, there is an -viewDidUnload method, which will be invoked from the system when the view has been unloaded because of low memory (please correct me: when exactly does this get called?)
-viewDidUnload is used to release all objects that were owned both by the view controller itself and the view. The reason: If a view controller holds references to childs of the view, i.e. a button, the referenced child views will not get released, because their retain count is >= 1. After they are released in -viewDidUnload, they can get freed up from memory.
Apple deprecated viewWillUnload, now you shoud use didReceiveMemoryWarning or dealloc to release your objetcs.
In iOS 6, the viewWillUnload and viewDidUnload methods of
UIViewController are now deprecated. If you were using these methods
to release data, use the didReceiveMemoryWarning method instead. You
can also use this method to release references to the view
controller’s view if it is not being used. You would need to test that
the view is not in a window before doing this.
If the view controller is popped from the navigation controller stack and is not retained anywhere else, it will be deallocated, and dealloc will be called instead of viewDidUnload. You should release the views created in loadView in dealloc, but it is not necessary to set the variables to nil, because soon after dealloc is called the variables will no longer exist.
You can release any subviews you hold on to, for example that UIImageView you retained in your loadView method, or better yet the image that was on that UIImageView.