Question

I'm in process of implementing "new game" functionality for one of my apps and ran into an issue where occasionally my code crashes because a notification is sent to a deallocated object. There are just a couple places where the notifications are being generated and consumed. I cleaned up code around those points, yet there are still occasional crashes.

I can think of two ways to avoid notifications - a centralized "data manager" class that can pass messages to different parts of the app or protocols and delegates. Both can be messy to implement, so my question is:

Is there a better way to write code without notifications when I only need to know about some change within 2 other classes within the app?

Is there a way to register for notifications using some kind of "weak self" reference to avoid having to deal with deallocated instances?

Was it helpful?

Solution

Generally delegation sounds much better for your situation. You can use blocks to implement the delegation if you want to minimise your code.

Ensure that all objects which are observers remove themselves from all observations in their dealloc method:

[[NSNotificationCenter defaultCenter] removeObserver:self];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top