使用nw_path_monitor_t时NSNotificationCenter发通知无法接收问题
问题根因与解决方法
1. 核心原因:NotificationReceiver实例提前释放(90%概率为此问题)
你在TestNWPathMonitor函数中把notification_receiver定义为局部栈变量,函数执行完成后该实例没有被任何强引用持有,ARC机制下会被立即回收,已经被销毁的对象自然无法接收后续触发的通知。
解决方案
将notification_receiver修改为全局持有对象,保证实例在监听周期内一直存活:
// 在文件顶部和monitor同级别定义全局强引用变量 static NotificationReceiver *g_notification_receiver; void TestNWPathMonitor () { PrintToFile("TestingNWPathMonitor\n"); // 赋值给全局变量,避免被ARC自动回收 g_notification_receiver = [[NotificationReceiver alloc] init]; [g_notification_receiver RegisterNotification]; monitor = nw_path_monitor_create (); nw_path_monitor_set_update_handler (monitor, WifiNetworkChangeCB); nw_path_monitor_start(monitor); }
2. 回调线程问题排查
nw_path_monitor默认回调执行在系统后台队列,NSNotificationCenter会在发送通知的线程同步执行观察者方法,虽然理论上不影响接收,但也可以手动指定回调队列为主队列排除线程异常:
monitor = nw_path_monitor_create (); // 新增指定回调运行在主线程 nw_path_monitor_set_queue(monitor, dispatch_get_main_queue()); nw_path_monitor_set_update_handler (monitor, WifiNetworkChangeCB); nw_path_monitor_start(monitor);
3. 其他可选排查点
- 检查注册和发送通知的字符串是否完全一致,避免大小写、拼写错误
- 在注册和发送通知的位置打印
[NSNotificationCenter defaultCenter]的内存地址,确认是同一个通知中心实例
内容的提问来源于stack exchange,提问作者NightFuryLxD
相关产品推荐
相关产品推荐

