Question

This isn't so much a question as a pondering thought - why does NSNotificationCenter throw an exception when it's released? I'm still new to iPhone development, and thus don't know the innards of Cocoa yet, so it'd be good to understand why.

I'm assigning the defaultCenter to a variable, calling addObserver:selector:name:object and then releasing the previous variable, but the call to [notify release] crashes the app. I'm not doing anything strange in the code, so it'd be interesting to find out exactly why it's doing this.

Anyone ran into this problem?

Was it helpful?

Solution

From what I know of NSNotifcation you shouldn't be assigning the defaultcenter to a variable but rather doing something like:

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

In that snippet your calling the default centre and registering the current object for a certain message.

And then to post a message to the notification centre you can use:

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

I use the above in all my code and don't have any problems with it.

OTHER TIPS

There should only be one default notification center for your app, so none of your classes should be retaining or releasing it. You wouldn't want your notification center to disappear on you, right?

I don't think you own the object, and therefore should not release it.

Remember the NARC: New Alloc, Retain, Copy. If you do one of these, you have to release it.

It's not yours to release.

Remember the NARC rule--you ONLY release things that you brought into existence using:

New Allocate Retain, or Copy.

NARC. See?

What you're doing with NSNotificationCenter is you're getting a copy of the singleton that represents the default notification center. It'd be worth reading up on singletons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top