CFNotificationCenter examples?

I'm still new to this, but with the help of examples, I learned very quickly. I am currently viewing messages from one running program to another, and CFNotificationCenter is the way forward. The only problem is that I cannot use it, and there seem to be no examples other than Apple VideoViewer.

Can someone provide a mini-example of how to configure it so that I can write one application for publishing a notification and another for receiving a test notification and doSomething () ;? Any help is much appreciated!

+4
source share
1 answer

Ok, I wrote a small CFNotificationCenter example. Typically, no one uses CoreFoundation for large projects, but instead uses Foundation. If you are really writing this project in Objective-C (as I assume from your tags), I would suggest using NSNotificationCenter . Without further consideration, here is an example:

#include <CoreFoundation/CoreFoundation.h> void notificationCallback (CFNotificationCenterRef center, void * observer, CFStringRef name, const void * object, CFDictionaryRef userInfo) { CFShow(CFSTR("Received notification (dictionary):")); // print out user info const void * keys; const void * values; CFDictionaryGetKeysAndValues(userInfo, &keys, &values); for (int i = 0; i < CFDictionaryGetCount(userInfo); i++) { const char * keyStr = CFStringGetCStringPtr((CFStringRef)&keys[i], CFStringGetSystemEncoding()); const char * valStr = CFStringGetCStringPtr((CFStringRef)&values[i], CFStringGetSystemEncoding()); printf("\t\t \"%s\" = \"%s\"\n", keyStr, valStr); } } int main (int argc, const char * argv[]) { CFNotificationCenterRef center = CFNotificationCenterGetLocalCenter(); // add an observer CFNotificationCenterAddObserver(center, NULL, notificationCallback, CFSTR("MyNotification"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately); // post a notification CFDictionaryKeyCallBacks keyCallbacks = {0, NULL, NULL, CFCopyDescription, CFEqual, NULL}; CFDictionaryValueCallBacks valueCallbacks = {0, NULL, NULL, CFCopyDescription, CFEqual}; CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &keyCallbacks, &valueCallbacks); CFDictionaryAddValue(dictionary, CFSTR("TestKey"), CFSTR("TestValue")); CFNotificationCenterPostNotification(center, CFSTR("MyNotification"), NULL, dictionary, TRUE); CFRelease(dictionary); // remove oberver CFNotificationCenterRemoveObserver(center, NULL, CFSTR("TestValue"), NULL); return 0; } 

In this example, an observer is created, a simple dictionary is placed on it, and the observer is deleted. For more information on CFNotificationCenter, see the Apple CFNotificationCenter Handbook .

+9
source

All Articles