gpt4 book ai didi

ios - 听 NSNotifications 的正确方法

转载 作者:行者123 更新时间:2023-11-28 18:56:01 27 4
gpt4 key购买 nike

如果我在 View Controller 上有 2 个通知有 2 个这样的观察者,这是否合适:

[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note1" object:nil];
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note2" object:nil];

或者我只是通过将 nil 传递给名称然后检查在 handleNotification 函数中发送的通知来找出运行了哪个通知:

[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:nil object:nil];

谢谢。

最佳答案

实际上,如果您将 nil 作为名称传递,您将收到所有通知,而不管它们的名称是什么(不仅仅是您想要的两个)。最好通过命名来分别订阅每一个。

苹果文档摘录:

If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.

(起初我不清楚这一点,我误读了它,认为您不会收到任何通知)。

您可以对两者使用相同的回调/监听器,并根据收到的通知决定要做什么。

您可以在 NSNotificationCenter 上创建一个类别来处理多个名称的注册,这就是类别的用途!

关于ios - 听 NSNotifications 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32777742/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com