Question

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
{
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

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