Sandro Meier
Sandro Meier

Reputation: 3051

Strange NSNotificationCenter crash

I have a problem with NSNotificationCenter. Now it crashes, but a few days ago, when I added the Notification, it worked properly. In the time between I added some code that has nothing to do with that.

I have about 10x10 tiles. Each tile adds itself as an observer as soon as it is created:

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

And in my player class, every time a jump ended, I post a Notification with the following code:

if (self.postNotifications == YES) {
    //Also post the notification for all the Tiles.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNot" object:self];
}

If I use NSLog() in the tiles, I can see that about 3 or 4 tiles receive the notification. And after that, the application crashes with a EXC_BAD_ACCESS. It says objc_msgSend() selector name: playerJumped. But I don't get why. I see that it works with the first one than it crashes. What's my error here? Can you please help me! Sandro

EDIT: Is there a Problem, because the Notification is received by about 100 objects?

Upvotes: 4

Views: 4860

Answers (2)

Tom Tallak Solbu
Tom Tallak Solbu

Reputation: 559

Had the same problem myself. Adding this to the class solved the problem

- (void) dealloc 
{

  [[NSNotificationCenter defaultCenter] removeObserver:self];

}

Upvotes: 10

hooleyhoop
hooleyhoop

Reputation: 9198

Your tile object has been deallocated but it is still registered with the notificationCenter to receive notifications. Try adding a breakpoint on the tile's -dealloc method if this isn't what you are expecting.

Upvotes: 9

Related Questions