Few questions: Lifecycle of UIViewController; release vs setting to nil - objective-c

I have a couple of questions relating to UIViewController:
1) When are each of the methods called for UIViewController? Specifically, the difference between viewDidLoad, viewDidUnload, and dealloc.
2) What's the difference, in general, when setting a pointer equal to nil and releasing the pointer? I know that in viewDidUnload you're supposed to set it equal to nil but in dealloc call release.
UPDATE: Sorry, just realized the question is misleading. Instead of dealloc, I meant -- when is initWithNibName:bundle: and release called? Just once by IB, right?

Setting a pointer to nil doesn't release the memory that it points to.
When you do something like
self.pointer = nil;
it's usually a case that the property has a retain attribute. When this is the case, setting the property to nil will indirectly cause a
[pointer release];
pointer = nil;
In the case of the view controller methods, viewDidLoad is called when your view is loaded, either from a nib, or programatically. More specifically, it's called just after -loadView is called. You shouldn't need to call loadView manually, the system will do it. The viewDidUnload method is called in the event of a memory warning and your view controller's view is not onscreen. Subsequently, loadView and viewDidLoad will get called again on demand.
The dealloc method, as normal, is called when your object's retain count reaches 0.

pointer = nil; // just clears the variable in which you store the pointer, but does not free memory.
[pointer release]; // just frees the object (memory), but does not clear the variable used to point to it.
self.pointer = nil; // sets the variable to nil. Also releases the object ONLY if pointer is a #property(retain) ivar.
One easy way to see when various methods are called is to do this in your UIViewController:
- (void)viewDidLoad
{
NSLog(#"MyViewController::viewDidLoad");
[super viewDidLoad];
// the rest of your viewDidLoad code, here.
}
// Etc., for the other methods of interest.
NOTE: much can be gleaned from overriding retain & release to log and then following along in the debugger.

Related

Delegates and retain cycles?

Edit: I'm really sorry. I edited the confusing errors I made in my post.
I have these ivars declared in WhereamiViewController.h:
CLLocationManager *locationManager;
IBOutlet MKMapView *worldView;
IBOutlet UITextField *locationTitleField;
The author writes that since WhereamiViewController owns locationManager and locationManager's delegate is the WhereamiViewController, locationManager delegate must be set to nil in the WhereamiViewController's dealloc method because the delegate is assigned instead of weak. In the .xib file worldView and locationTitleField are set to delegate the File's Owner, but why don't those two delegates need to be set to nil when both of them are also assign instead of weak?
PS: It's using ARC
locationManager must be set to nil in the WhereamiViewController's dealloc method
The CLLocationManager does not retain its delegate. Even if it did setting the locationManager to nil in dealloc will do nothing to break a retain cycle because a retain cycle would result in dealloc never being called. There needs to be some other event that breaks the retain cycle such as dismissing/popping the view controller.
but why don't those two need to be set to nil?
If t is documented that the class does not retain the delegate then you do not have to worry about a retain cycle. Sometimes the documentation comes from just looking at the header file and looking for assign rather than strong or retain. CLLocationManager does not retain its delegate so you do not have to assign locationManager to nil. If, however, the locationManager may still receive events after your class is deallocated you should set its delegate to nil in the dealloc method to prevent callbacks after your class is deallocated.
- (void)dealloc
{
//Prevent callbacks after dealloc
//Useful if locationManager is a singleton or used elsewhere
locationManager.delegate = nil;
[locationManager release]; //If not ARC
[super dealloc];//If not ARC
}
Well you need to set it to nil simply as a precautionary measure. Did I Confuse you? Let me explain.
The setting to nil has really nothing to do with retain release cycle, it is simply to avoid locationManager sending delegate call to your controller. For instance, if locationManager is updating location meanwhile your controller is released, the locationManager still having the delegate reference set to your view controller, will call the delegate with location parameters.
But since you controller has been deallocated, the call will result in bad memory access.
However, if you set it to nil, exception will not be thrown since manipulatin of nil pointers has no affect.
locationManager must be set to nil in the WhereamiViewController's dealloc method.
That doesn't do anything.
If you are using manual reference counting, it should be released in WhereamiViewController's dealloc (because WhereamiViewController owns it). If you have a property that wraps the locationManager instance variable, you can set that property to nil in dealloc to achieve the same effect, as long as the property is a retain property. However, using properties in dealloc is generally discouraged by Apple.
If you re using ARC, the compiler will do all that for you.
What you should be doing in WhereamiViewController's dealloc, is setting the location manager's delegate to nil because, if the location manager survives beyond the dealloc, you do not want it sending delegate messages to the non existent WhereamiViewController.
Again, with ARC if the delegate of CLLocationManager is a weak reference, the nilling is done for you.
but why don't those two need to be set to nil?
They don't, but the same reasoning applies to their delegates, when their delegates get deallocated.

Setting the object parameter to nil in Objective-C

I have an ivar that is a UIPopoverController. When it gets dismissed, I want to clean up memory. I call the following method when the popover gets dismissed, or if the user pressed the BarButtonItem when the popover is already being presented to the user.
- (void)popoverCleanup:(UIPopoverController *)popoverController {
popoverController.delegate = nil;
popoverController = nil;
}
I set a breakpoint and tried following the code and looking at the memory. I see that my ivar Popover and the method parameter popoverController both point to the same memory address. When I hit the first line, I see the delegate set to nil on both the Popover and popoverController parameter. When I reach the end of the method however, I see only popoverController's memory set to nil, whereas the ivar Popover does not get set to nil. Is there a reason for this?
Thanks.
By doing this, you are just saying you don't want to hold a popoverController pointer, no matter to what it points. Nothing get's released here. Proper way to release a popover is implementing it's delegate method for dismissing and release it there.
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
[popoverController release];
}
Keep in mind that setting an ivar to nil doesn't release the object that ivar was pointing to, it usually leaks it. You can only do that with copied or retained properties because they work so that the retain or copy the new value (nil, which does nothing when retained or copied as it's not really an object) and release the old one. You should only set the ivar to nil after releasing it so that if you accidentally send it a message later, you don't crash for accessing released memory.
Edit: also keep in mind that there is really no need for ivar if you only want to present a popover and release it. Just create a local variable and present a popover. Once delegate method gets called it will have a pointer to the popover object, no need to keep ivar just for that. Only case where you would need an ivar for popover is if you wanted to create it and present it multiple times, then release it when done with it forever, like when leaving view controller from which you presented it.
This is because popoverController and your instance variable are not the same variable even though they point to the same thing (same pointer instance before you set it to nil).
In that method (- (void)popoverCleanup:(UIPopoverController *)popoverController) you need to set your instance variable to nil rather than popoverController variable. Also if you are not already, you'd need to release your popover and it should set the instance variable to nil if there is nothing else retaining it
It should be noted that setting an instance variable to nil does not release the object pointed to.
If you want to release the object, the simplest thing is to have it managed as a property and set the property to nil.
Bear in mind that popoverController = nil; is not the same as self.popoverController = nil;. The former is setting the INSTANCE VARIABLE to nil. The latter is setting the PROPERTY to nil, and if the property is defined with "retain", the the addressed object will be released.

Easy pattern for releasing properties

I have a general question regarding memory management of properties. Currently, I always use properties without any explicit declaration of related ivars. And, for every retained or copied property I'm releasing its retain count both in dealloc and viewDidUnload methods:
-(void)dealloc{
[self.myProperty release];
[self.myOutlet release];
[super dealloc];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myProperty = nil;
self.myOutlet = nil;
}
Now, I know that only the outlets and properties retained by the main view should be set to nil in viewDidUnload, and the rest properties should be released in dealloc. But hey, why do I have to bother for every property where it must be released - in dealloc or in viewDidUnload? If some property will be released twice it's OK because it wouldn't crash the app by sending a message to nil object. Putting release in both places (dealloc and unload) saves time and prevents from bugs later when doing code refactoring and forgetting to change release place. Any critics and shouting on that? :)
If you're using property accessors in -dealloc because you don't have access to the ivar directly, you should do the same in -dealloc that you do in -viewDidUnload:
self.myProperty = nil;
The point of using -release in -dealloc is to avoid calling the accessor, which conceivably could have been overridden by a subclass to have side effects that you don't want in -dealloc, when everything else from the subclass has already been deallocated. But if you're already calling the accessor in -dealloc, you might as well use the setter to release the ivar and ensure that it's done right.
The difference between -dealloc and -viewDidUnload is that you're still working with a complete, fully functional object in -viewDidUnload, whereas the object may already be partially deallocated in -dealloc.
My previous answer on this discusses what Apple recommends and why. Relevant portions reproduced here for clarity:
Also, from the Apple docs on -viewDidUnload:
The preferred way to relinquish ownership of any object (including those in outlets) is to use the corresponding accessor method to set the value of the object to nil. However, if you do not have an accessor method for a given object, you may have to release the object explicitly
So, there you go. If your outlet has a property associated with it (which they all should anymore), then nil it in -viewDidUnload -- but don't release it. This makes sense when you consider what is actually happening in a synthesized accessor; the code looks something like this:
- (void) setMyView1 : (UIView *) view {
if (myView1) // the associated IVAR is already set
[myView1 release];
myView1 = [view retain];
}
As you can see, setting a synthesize property to nil implicitly releases the retained object.
Also from the docs in regards to -dealloc:
If you implement this method but are building your application for iOS 2.x, your dealloc method should release each object but should also set the reference to that object to nil before calling super.
Unless you are supporting iOS2.x, there is no need to set objects to nil in dealloc.
So, to summarize Apple's docs regarding -viewDidUnload and -dealloc:
In -viewDidUnload, nil properties (including IBOutlet properties), but don't release them
In -dealloc release properties, but don't nil them (unless building for 2.x).

NSTableViewDataSource dealloc in objective-c

I'm currently learning objective-c and I'm currently training with NSTableView.
Here is my problem :
I have linked my tableview to my controller through Interface Builder so that it has a datasource, I have implemented NSTableViewDataSource protocol in my controller and I have implemented both -(NSInteger) numberOfRowsInTableView: and -(id) tableView:objectValueForTableColumn:row: methods.
I have created a raw business class ("person") and I succeeded to display its content into my NSTableView.
But then, I put some NSLog in my dealloc methods to see whether the memory was freed or not and it seems that my array as well as my "person" instances are never released.
here is my dealloc code in the controller:
-(void)dealloc
{
NSLog(#"the array is about to be deleted. current retain : %d",[personnes retainCount]);
[personnes release];
[super dealloc];
}
and in my "person" class
-(void) dealloc
{
NSLog(#"%# is about to be deleted. current retain : %d",[self prenom],[self retainCount]);
[self->nom release];
[self->prenom release];
[super dealloc];
}
When these deallocs are supposed to be called in the application lifecycle? Because I expected them to be called at the window closure, but it didn't.
In the hope of beeing clear enough,
Thanks :)
KiTe.
I’m assuming you’re never releasing the window controller object that owns the (only) window. As such, the window controller and every top level object in the nib file are retained throughout the application lifecycle, including the window (and its views).
Since the window controller exists throughout the application lifecycle, it isn’t released, hence its -dealloc method is never called. And, since the controller -dealloc method is never called, its personnes array isn’t released.
The personnes array owns its elements. Since the array isn’t released, neither are its elements, hence the -dealloc method of the corresponding class/instances is never called.
Don't ever use retainCount. The results are misleading at best. If you practice proper memory management practices, you'll be fine. Have you had any memory issues/crashes?

Checking if an object has been released before sending a message to it

I've only recently noticed a crash in one of my apps when an object tried to message its delegate and the delegate had already been released.
At the moment, just before calling any delegate methods, I run this check:
if (delegate && [delegate respondsToSelector:...]){
[delegate ...];
}
But obviously this doesn't account for if the delegate isn't nil, but has been deallocated.
Besides setting the object's delegate to nil in the delegate's dealloc method, is there a way to check if the delegate has already been released just incase I no longer have a reference to the object.
No. There is no way to tell whether a variable points to a valid object. You need to structure your program so that this object's delegate isn't going away without letting it know first.
I assume you're not using GC. In that case, standard convention is that the code that sets the delegate is responsible for setting the delegate-user's reference to nil before allowing the delegate to be deallocated. If you're using GC, you can use a __weak reference for the delegate, allowing the garbage collector to set the reference to nil when the instance is garbage collected.
how about using a counter that you increment everytime you alloc and decrement everytime you dealloc. That way you could detect double allocs and could decide not to use a delegate if the counter isnt nil but the address isnt nil also
for debug proposes you can override release method on your class to see when it is called.
-(oneway void)release
{
NSLog(#"release called");
[super release];
}