NSNotificationCenter 可能会导致错误。你知道更优雅的解决方案吗?

发布于 2025-01-06 10:59:59 字数 741 浏览 4 评论 0原文

我可以将观察者两次(意外地)添加到通知中心,并且我将收到两次通知。 是否可以只收到一份通知?你知道更优雅的解决方案吗?

我向您展示这个示例是因为这可能会导致错误。

- (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏九 2025-01-13 11:00:00

如果您不确定是否在其他地方添加了观察者,则可以在每次添加观察者时使用以下代码,

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

这样您就可以删除旧的观察者(如果存在)并添加新的观察者。

这不是 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

[[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.

七禾 2025-01-13 11:00:00

您还可以将一个对象设置为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文