简体   繁体   中英

How can I send a userInfo dict using CFNotificationCenterGetDarwinNotifyCenter()

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM