NSNotificationCenter 可能会导致错误。你知道更优雅的解决方案吗?
我可以将观察者两次(意外地)添加到通知中心,并且我将收到两次通知。 是否可以只收到一份通知?你知道更优雅的解决方案吗?
我向您展示这个示例是因为这可能会导致错误。
- (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
{
}
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
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不确定是否在其他地方添加了观察者,则可以在每次添加观察者时使用以下代码,
这样您就可以删除旧的观察者(如果存在)并添加新的观察者。
这不是 100% 的失败证明,但它是一个开始。在调用异步或其他特殊情况的多线程应用程序中,这可能会失败。
If you're not sure if you added the observer somewhere else, you can use the following code everytime you're adding an Observer
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.
您还可以将一个对象设置为 nil,然后使用该对象,就像它仍然有效一样。
并非所有事情都能做到万无一失。
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.