我想在 Objective-C 中创建一个用户代理,用于监听来自默认 NSDistributedNotificationCenter
的通知。代理将没有 GUI。然而,当我在 Xcode 中创建 Cocoa 应用程序(我还将使用分布式对象,我认为这仅在 Cocoa 中)时,Xcode 将项目设置为 GUI 应用程序。
在主函数中,我删除了 NSApplicationMain(...)
函数调用,以从应用程序中删除 GUI 元素。但是,现在我无法让线程等待(监听)来自 NSDistributedNotificationCenter
的通知。该应用程序刚刚启动并立即退出。
我研究了使用当前NSThread
中的NSRunLoop
,但是,NSRunLoop
似乎只等待NSPort
s。没有提到等待 NSNotifications
。
最佳答案
NSDistributedNotificationCenter
是 Foundation,因此您不需要创建 GUI 应用程序。例如,您可以创建命令行模板,然后从终端运行它。作为一个非常简单的示例,您可以创建一个仅打印下面收到的每个分布式通知的示例。
要构建,请复制到 Foundation 命令行应用程序的 Xcode 模板中,或者简单地复制到名为 test_note.m 之类的文本文件中,然后根据注释进行构建。在此示例中,应用程序将永远不会结束(CFRunLoopRun()
永远不会返回),您必须通过从终端按 CTRL+C 来终止它,或者使用 kill
之类的方式终止它。 code> 或事件监视器。
// test_build.m
// to build: clang -o test_build test_build.m -framework foundation
#import <Foundation/Foundation.h>
@interface Observer : NSObject
- (void)observeNotification:(NSNotification*)note;
@end
@implementation Observer
- (void)observeNotification:(NSNotification*)note
{
NSLog(@"Got Notification: %@", note);
}
@end
int main (int argc, char const *argv[])
{
@autoreleasepool {
Observer* myObserver = [[Observer alloc] init];
[[NSDistributedNotificationCenter defaultCenter] addObserver:myObserver selector:@selector(observeNotification:) name:nil object:nil];
CFRunLoopRun();
}
return 0;
}
关于objective-c - 使用 NSDistributedNotificationCenter 在 Objective-C 中开发非 GUI 用户代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8498688/