Reputation: 22926
In my Application I listen for keyboard notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow)
name:UIKeyboardWillShowNotification
object:nil];
I have just removed a bug which caused a crash in my app,
I have a modal view with a UI (which gets destroyed and recreated each time it's presented.
I was getting a crash the second time I went to use it before I added this line of code:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Any one know why not removing observer for a dealloced object caused a crash?
Upvotes: 4
Views: 302
Reputation: 2040
NSNotificationCenter
maintains references to objects that may or may not have been dealloc'd. The crash occurs the second time because NSNotificationCenter doesn't know that the old UIViewController has been totally released.
Upvotes: 1
Reputation: 200
This is because when you get the notification, if you havent removed your class as an observer, it still tries calling the method. However, since the object has been completely deallocated and destroyed, you get an EXC_BAD_ACCESS.
Upvotes: 3
Reputation: 1389
It is a good idea to remove any observers in the dealloc method for a class. Otherwise the notification is sent to an object that no longer exists, which crashes.
Upvotes: 1