NSNotificationCentre Crash

In my application, I listen to keyboard notifications:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil]; 

I just removed the error that caused the crash in my application,

I have a modal view with a user interface (which is destroyed and recreated every time it is presented).

I got a crash the second time I started using it before adding this line of code:

 [[NSNotificationCenter defaultCenter] removeObserver:self]; 

Does anyone know why not remove the observer for the freed object caused by the failure?

+4
source share
3 answers

This is due to the fact that when you receive a notification, if you did not delete your class as an observer, it still tries to call the method. However, since the object was completely freed and destroyed, you will get EXC_BAD_ACCESS.

+3
source

It is recommended that you remove any observers in the dealloc method for the class. Otherwise, a notification is sent to the object that no longer exists, which fails.

+1
source

NSNotificationCenter maintains references to objects that may or may not be deleted. The failure occurs a second time because the NSNotificationCenter does not know that the old UIViewController is completely freed.

+1
source

Source: https://habr.com/ru/post/1496242/


All Articles