Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-c NSNotificationCenter Bad Access

So I have a CCLayer object which has a child CCSprite object, when a condition happens (detected by an update method) a method of the CCSprite is called which itself calls the following

[[NSNotificationCenter defaultCenter] postNotificationName:@"mymethod" object:nil];

the CCLayer then goes on to run

[node removeFromParentAndCleanup:YES];

for the CCSprite to remove it. The CCLayer also called the following on init

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mymethod) name:@"mymethod" object:nil];

Now 9 times out of 10 this is fine and works as expected however occasionally I get a bad_access pointing to the notification post line.

My guess from reading about other people having similar issues is that this is because the child object has been removed, but I don't know how else to do it as it is being called before it is removed.

Could something be happening to delay the post notification being called and it is ending up being called after the object is removed or am I barking up the wrong tree?

UPDATE

Added removal code above, if I comment out the remove and cleanup line it doesn't happen.

like image 647
Jacob Tomlinson Avatar asked Nov 20 '13 17:11

Jacob Tomlinson


1 Answers

You need to remove the observer. Observers don't get removed automatically, so if you are not removing them then you stack them in memory, that could be the reason that it breaks later.

like image 124
AntonijoDev Avatar answered Oct 14 '22 22:10

AntonijoDev