How can I send a userInfo dict using CFNotificationCenterGetDarwinNotifyCenter()

风流意气都作罢 提交于 2019-12-10 20:05:48

问题


I need to send an object using CFNotificationCenterGetDarwinNotifyCenter() however, I'm noticing that whenever I send a notification using

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);

then I find that in the observer callback, the userInfo dict is NULL. Is there something I am missing here? Is there some other way by which I can possibly send the userInfo object? I was looking at http://nshipster.com/inter-process-communication/ and the Distributed Notifications part, however whenever I use :

CFNotificationCenterRef distributedCenter =
CFNotificationCenterGetDistributedCenter();

then I get an error Invalid Use of Function error whenever I try it.


回答1:


If you read the documentation for CFNotificationCenterGetDarwinNotifyCenter, you'll find this caveat:

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

userInfo is one of those parameters. CFNotificationCenter.h goes into more detail:

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

Why? Dig a little deeper. The documentation also mentions that this type of notification center is built on the Core OS notify mechanism declared in notify.h. If you look that up, you'll find that there is only one way to post a notification, by calling notify_post(), which takes only a single string argument. There is no way to add additional data to the notification. This is a very old and rudimentary IPC mechanism that doesn't know anything about CoreFoundation data structures.

As for CFNotificationCenterGetDistributedCenter, that isn't available on iOS.



来源:https://stackoverflow.com/questions/37246107/how-can-i-send-a-userinfo-dict-using-cfnotificationcentergetdarwinnotifycenter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!