문제

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
{
}
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top