views:

103

answers:

4

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?

+2  A: 

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?

kubi
Oh right, so I'm assigning a *reference* then and not a new object. Ahh, that makes sense. Thanks!
Jamie Rumbelow
+1  A: 

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.

Emil
Word of advice, since @Jamie is new to Cocoa dev: Don't ever look at the `retainCount` of a variable, it will only cause confusion. There are many valid reasons that a retain count can be different than what you expect. As long as you follow proper memory management practices, everything will work as it should.
kubi
The second part of @Emil's answer, about AllocRetainCopy, is right on, though. Good advice.
kubi
Yep, memory management is certainly scary - I'm being really careful to release everything the moment I'm done with it - keeping on track of properties is pretty difficult though. Thanks!
Jamie Rumbelow
The first part of your answer is very bad advice. The second part is pretty good.
Alex
Yeah, I dind't think of that. Edited now :)
Emil
+5  A: 

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.

James Raybould
A: 

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.

Dan Ray