Question

In my app I have a few VCs that need to receive NSNotifications from my model, which is fetching data asynchronously. The problem is that the VCs disappear from time to time and when the model finishes fetching data and tries to send a notification to a VC that is already gone, the app crashes. Is there an option to prevent this crashing? Like telling NSNotificationCenter "it's ok if the observer is not there"?

:)

// Subscribe for notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedLoading) name:@"Finished Loading" object:nil];

// Model sends a notification to a subscribed VC
[[NSNotificationCenter defaultCenter] postNotificationName:@"Finished Loading" object:nil userInfo:nil];
Was it helpful?

Solution

Apple Documentation:

Be sure to invoke this method (removeObserver: or removeObserver:name:object:) before notificationObserver or any object specified in addObserver:selector:name:object: is deallocated.

add the removeObserver call to dealloc of observer.

- (void)dealloc{
...
[[NSNotificationCenter defaultCenter] removeObserver:self ];
...
}

OTHER TIPS

I think, you just need to do:

[[NSNotificationCenter defaultCenter] removeObserver:self ];

You have to call NSNotificationCenter removeObserver... for each time you call addObserver.... This is typically done in the dealloc method.

To be honest, with this approach you are mitigating the symptoms rather than curing the disease.

If you are using an asynchronous networking library such as AFNetworking to return NSOperation instances, then you would be better to manage these in an NSOperationQueue. Then, when your controller is popped, in the viewWillDisappear method, cancel all outstanding asynchronous requests:

[myOpQueue cancelAllOperations];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top