Voloda2
Voloda2

Reputation: 12597

NSNotificationCenter can lead to bugs. Do you know more elegant solutions?

I can add observer twice (by accident) to the notification center and I will get notifications twice. Is it possible to get only one notification? Do you know more elegant solutions?

I show you this example because this may lead to bugs.

- (void)viewDidLoad 
{
 [[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardDidShow:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardDidShow:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];
}

- (void)keyboardDidShow:(NSNotification *)ntf
{
}

Upvotes: 1

Views: 564

Answers (2)

Cocoa Dev
Cocoa Dev

Reputation: 9541

If you're not sure if you added the observer somewhere else, you can use the following code everytime you're adding an Observer

[[NSNotificationCenter defaultCenter] removeObserver:self name:aName object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:aSelector name:aName object:nil];

This way you are removing the old one (if it existed) and adding a new one.

It's not 100% fail proof but it's a start. This could fail in Multi-Threaded apps where the calls are being made async or other unique situations.

Upvotes: 1

bbarnhart
bbarnhart

Reputation: 6710

You can also set an object to nil and then later use that object as if was still valid.

Not everything can be made fail safe.

Upvotes: 1

Related Questions