【发布时间】:2021-12-07 07:41:49
【问题描述】:
我有一个函数,它使用nw_path_monitor_t 注册网络事件。
// Entry point.
// Will be called from AppDelegate when app starts up
void TestNWPathMonitor () {
PrintToFile("TestingNWPathMonitor\n");
NotificationReceiver *notification_receiver = [[NotificationReceiver alloc] init];
// Set up the notification receiver to listen for wifi notification
[notification_receiver RegisterNotification];
monitor = nw_path_monitor_create ();
nw_path_monitor_set_update_handler (monitor, WifiNetworkChangeCB);
nw_path_monitor_start(monitor);
}
我已经提供了回调,它会在网络事件发生变化时被调用。在回调中(如下所示),我正在寻找 wifi 事件并将通知发布到 default notification center。
nw_path_monitor_update_handler_t WifiNetworkChangeCB = ^ (nw_path_t path) {
PrintToFile("Wifi Network change!!\n");
nw_path_status_t status = nw_path_get_status (path);
if (nw_path_uses_interface_type (path, nw_interface_type_wifi)) {
if (status == nw_path_status_satisfied) {
PrintToFile("nw_path_status_satisfied\n");
[[NSNotificationCenter defaultCenter] postNotificationName:@"WifiNetworkChange" object:nil];
} else {
PrintToFile("!(nw_path_status_satisfied)\n");
}
}
};
这是 NotificationReceiver 类:
// NotificationReceiver.h
#include <Foundation/Foundation.h>
@interface NotificationReceiver : NSObject
- (void) HandleNotification : (NSNotification *) pNotification;
- (void) RegisterNotification ;
@end
// NotificaitonReceiver.m
@implementation NotificationReceiver
- (void) HandleNotification : (NSNotification *) pNotification {
PrintToFile([[NSString stringWithFormat:@"Received notification: %@\n", pNotification.name] UTF8String]);
}
- (void) RegisterNotification {
PrintToFile("RegisterNotification!\n");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HandleNotification:) name:@"WifiNetworkChange" object:nil];
}
@end
在开始时调用的RegisterNotification(如第一个代码sn-p所示)会将实例添加为observer,并且HandleNotification是从WifiNetworkChangeCB块发布的wifi通知的接收者。
问题是,当我收到wifi事件时,调用了WifiNetworkChangeCB并执行了postNotificationName函数(已通过调试器验证),但HandleNotification没有收到通知。
我得到以下输出:
TestingNWPathMonitor
RegisterNotification!
Wifi Network change!!
而预期的输出是:
TestingNWPathMonitor
RegisterNotification!
Wifi Network change!!
Received notification: WifiNetworkChange
我已阅读通知中心的documentation 了解其用法。也提到了这个answer。 我还参考了我正在使用的函数的文档(在解释问题时将它们添加为超链接),一切似乎都很好。
但我显然遗漏了一些东西(因为它不起作用)。任何帮助将不胜感激。
【问题讨论】:
-
init
NotificationReceiver在哪里?难道是它被释放得太早了? -
@Larme
NotificationReceiver的 init 在TestNWPathMonitor函数中调用(第一个代码 sn-p)。我还没有走到尽头,所以还没有移除观察者或停止路径监视器。 -
TestNWPathMonitor () 范围告诉我们,
monitor是全局的,NotificationReceiver *notification_receiver不是。因此,当通知表明满意的工作时,notification_receiver不再存在。您也可以通过在 main.m 中添加观察者来证明这个概念。 ps:在objc中methodnames以小写字母开头,当setter & getter违反“camelCased”methodname规则时,你会遇到麻烦。 -
@OlSen 哇,谢谢。这就是问题所在。在我将
NotificationReceiver *notification_receiver设为全局后,我能够获得预期的输出。将此作为答案,以便我可以将此帖子标记为“已解决”? -
@OlSen 我来自 C++ 背景。由于 'NotificationReceiver *notification_receiver' 是一个指针,我认为它会超出函数的范围。谢谢。
标签: ios objective-c macos nsnotificationcenter nwpathmonitor