ios - 如何使用 CFNotificationCenterGetDarwinNotifyCenter() 发送 userInfo 字典

标签 ios core-foundation cfnotification

我需要使用 CFNotificationCenterGetDarwinNotifyCenter() 发送对象,但是,我注意到每当我使用

发送通知时
const void *tkeys[1] = { @"testKey" };
const void *tvalues[1] = { @"testValue" };
CFDictionaryRef userInfo = CFDictionaryCreate(NULL, tkeys, tvalues, 1, NULL, NULL);
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(),
                                       CFSTR("foo"),
                                       object,
                                       userInfo,
                                       true);

然后我发现在观察者回调中,userInfo dict 为 NULL。我在这里缺少什么吗?有没有其他方法可以发送 userInfo 对象?我在看http://nshipster.com/inter-process-communication/和分布式通知部分,但是每当我使用:

CFNotificationCenterRef distributedCenter =
CFNotificationCenterGetDistributedCenter();

然后我每次尝试时都会收到错误 Invalid Use of Function 错误。

最佳答案

如果您阅读 the documentation for CFNotificationCenterGetDarwinNotifyCenter ,你会发现这个警告:

Several function parameters are ignored by Darwin notification centers. To ensure future compatibility, you should pass NULL or 0 for all ignored arguments.

userInfo 是这些参数之一。 CFNotificationCenter.h 更详细:

// For this center, there are limitations in the API. There are no notification "objects",
// "userInfo" cannot be passed in the notification, ...
// - CFNotificationCenterPostNotification(): the 'object', 'userInfo', and 'deliverImmediately' arguments are ignored.

为什么?挖得更深一点。该文档还提到这种类型的通知中心是建立在 notify.h 中声明的 Core OS 通知机制之上的。 .如果你查一下,你会发现只有一种方法可以发布通知,即调用 notify_post()。 ,它只接受一个字符串参数。无法向通知添加其他数据。这是一个非常古老和基本的 IPC 机制,它对 CoreFoundation 数据结构一无所知。

至于 CFNotificationCenterGetDistributedCenter,在 iOS 上不可用。

关于ios - 如何使用 CFNotificationCenterGetDarwinNotifyCenter() 发送 userInfo 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37246107/

相关文章:

ios - PhoneGap 应用程序在显示内存警告后崩溃

iphone - 是否有用于获取 twitter xml 或 json 输出的引擎?

ios - iOS 中的总屏幕解锁时间计算

objective-c - 如何找到 os x 上所有事件窗口的根元素

ios - 在 iOS 中检查设备屏幕打开或关闭

ios - 在应用程序委托(delegate)中下载 firebase 数据

ios - 调整超过 2 个元素的内容压缩和拥抱属性

iphone - 创建自定义 CFDictionary 回调

xcode - 确定在 Swift 中创建对称 key 异常的原因