gpt4 book ai didi

objective-c - CFNotificationCenter 用法示例?

转载 作者:太空狗 更新时间:2023-10-30 03:59:43 25 4
gpt4 key购买 nike

我对此还是很陌生,但借助示例,我的学习速度非常快。我目前正在研究将通知从一个正在运行的程序发布到另一个程序,而 CFNotificationCenter 是前进的方向。唯一的问题是,我无法使用它,而且除了 apple 的 videoviewer 之外似乎没有任何示例。

谁能提供一个关于如何设置它的小例子,这样我就可以编写一个应用程序来发布通知,一个应用程序来接收测试通知和 doSomething();?非常感谢任何帮助!

最佳答案

好吧,我写了一个 CFNotificationCenter 的小例子。一般来说,大型项目没有人使用 CoreFoundation,而是使用 Foundation。如果你真的在 Objective-C 中编写这个项目(正如我从你的标签中假设的那样),我建议使用 NSNotificationCenter .事不宜迟,这里是示例:

#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;
}

这个例子创建了一个观察者,向它发送了一个简单的字典,然后删除了观察者。有关 CFNotificationCenter 的更多信息,请访问 Apple's CFNotificationCenter Reference .

关于objective-c - CFNotificationCenter 用法示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6968677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com