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!!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With