views:

450

answers:

3

In my question about using a delegate or a UIControl Event, this was in Kendall Helmstetter Geln's answer:

Both are about an equal load to work with - with a delegate you have to set yourself and then remember to unset yourself before you are deallocated. You have to do the same thing with notifications, remember to start listening and then unsubscribe before you are deallocated.

What do they mean, unsubscribe before deallocated, unset yourself? I haven't been doing whatever that is. Could someone please explain what it is and how to do it?

Thanks!!

A: 

I believe you simply set the delegate to nil.

myOjectOrClass.delegate = nil;
John Ballinger
So you have to do this for every delegate you assign? What happens if you don't? What about events (with [control addTarget:self action:....) ?
Mk12
And how come in my book and in example code I've never seen this?
Mk12
+4  A: 

You need to remove yourself as delegate if your lifespan is shorter than the object you are delegate for. In almost all cases your lifespan is equal to or longer than the object you are delegate for. That said, it's a good habit to get into. Consider the case where you are the delegate for a UITableView. In -init, perhaps you call:

self.myTableView.delegate = self;

Then it would potentially be wise in -dealloc to say

_myTableView.delegate = nil;
[_myTableView release];
_myTableView = nil;

The reason to do this is that myTableView may be retained by other objects, so may not deallocate when you release it. If it makes a delegate call after you are gone, your application will crash. So clearing the delegate pointer is a good idea here.

Similarly for NSNotificationCenter, you should remove yourself in -dealloc thus:

[[NSNotificationCenter defaultCenter] removeObserver:self];

This removes you from all observations. You should do this in -dealloc if your class ever registers for any notifications. If you don't do this, and a notification you were observing comes in after you're gone, the app will crash.

This is not necessary for NSTimers because NSTimers retain their target (you).

Rob Napier
Thanks! And What about UIControl Events? Should I do [myButton removeTarget: ....] ?
Mk12
And does this also apply to DataSources?
Mk12
For UIControl, it's an interesting question. I'm not sure if addTarget:... retains. If it doesn't, then you're right, you should probably remove yourself. Datasources are identical to delegates.
Rob Napier
Anyone else know for sure about UIControl Events?
Mk12
A: 

No retain is performed against the target when passed to the UIControl addTarget method. Although the documentation doesn't make specific mention of this, I have written a simple test to prove out this fact.

If you add a target as an observer of a control's event and then release it you will notice the retain count go down (potentially resulting in it getting reclaimed).

This means that the control will never prevent the target from being deallocated.

simeon