Easy pattern for releasing properties - objective-c

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).

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.

Do I set properties to nil in dealloc when using ARC?

I am trying to learn Automatic Reference Counting in iOS 5. Now the first part of this question should be easy:
Is it correct that I do NOT need to write explicit
release-property statements in my dealloc when using ARC? In other
words, is it true that the following does NOT need a explicit
dealloc?
#interface MyClass : NSObject
#property (strong, nonatomic) NSObject* myProperty;
#end
#implementation MyClass
#synthesize myProperty;
#end
My next and more important question comes from a line in the Transitioning to ARC Release Notes document:
You do not have to (indeed cannot) release instance variables, but you may need to invoke [self setDelegate:nil] on system classes and other code that isn’t compiled using ARC.
This begs the question: how do I know which system classes are not compiled with ARC? When should I be creating my own dealloc and explicitly setting strongly retaining properties to nil? Should I assume all NS and UI framework classes used in properties require explicit deallocs?
There is a wealth of information on SO and elsewhere on the practices of releasing a property's backing ivar when using manual reference tracking, but relatively little about this when using ARC.
Short answer: no, you do not have to nil out properties in dealloc under ARC.
Long answer: You should never nil out properties in dealloc, even in manual memory management.
In MRR, you should release your ivars. Nilling out properties means calling setters, which may invoke code that it shouldn't touch in dealloc (e.g. if your class, or a subclass, overrides the setter). Similarly it may trigger KVO notifications. Releasing the ivar instead avoids these undesired behaviors.
In ARC, the system automatically releases any ivars for you, so if that's all you're doing you don't even have to implement dealloc. However, if you have any non-object ivars that need special handling (e.g. allocated buffers that you need to free()) you still have to deal with those in dealloc.
Furthermore, if you've set yourself as the delegate of any objects, you should un-set that relationship in dealloc (this is the bit about calling [obj setDelegate:nil]). The note about doing this on classes that aren't compiled with ARC is a nod towards weak properties. If the class explicitly marks its delegate property as weak then you don't have to do this, because the nature of weak properties means it'll get nilled out for you. However if the property is marked assign then you should nil it out in your dealloc, otherwise the class is left with a dangling pointer and will likely crash if it tries to message its delegate. Note that this only applies to non-retained relationships, such as delegates.
Just to give the opposite answer...
Short answer: no, you don't have to nil out auto-synthesized properties in dealloc under ARC. And you don't have to use the setter for those in init.
Long answer: You should nil out custom-synthesized properties in dealloc, even under ARC. And you should use the setter for those in init.
The point is your custom-synthesized properties should be safe and symmetrical regarding nullification.
A possible setter for a timer:
-(void)setTimer:(NSTimer *)timer
{
if (timer == _timer)
return;
[timer retain];
[_timer invalidate];
[_timer release];
_timer = timer;
[_timer fire];
}
A possible setter for a scrollview, tableview, webview, textfield, ...:
-(void)setScrollView:(UIScrollView *)scrollView
{
if (scrollView == _scrollView)
return;
[scrollView retain];
[_scrollView setDelegate:nil];
[_scrollView release];
_scrollView = scrollView;
[_scrollView setDelegate:self];
}
A possible setter for a KVO property:
-(void)setButton:(UIButton *)button
{
if (button == _button)
return;
[button retain];
[_button removeObserver:self forKeyPath:#"tintColor"];
[_button release];
_button = button;
[_button addObserver:self forKeyPath:#"tintColor" options:(NSKeyValueObservingOptions)0 context:NULL];
}
Then you don't have to duplicate any code for dealloc, didReceiveMemoryWarning, viewDidUnload, ... and your property can safely be made public. If you were worried about nil out properties in dealloc, then it might be time you check again your setters.

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];
}

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

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.