Jamie Rumbelow
Jamie Rumbelow

Reputation: 5095

Why does NSNotificationCenter throw an exception when I release it?

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?

Upvotes: 0

Views: 437

Answers (4)

Emil
Emil

Reputation: 7256

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.

Upvotes: 1

Dan Ray
Dan Ray

Reputation: 21893

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.

Upvotes: 0

James
James

Reputation: 5820

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.

Upvotes: 5

kubi
kubi

Reputation: 49354

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?

Upvotes: 2

Related Questions