我想在Objective-C中创建一个用户代理,用于侦听来自默认NSDistributedNotificationCenter
的通知。代理将没有GUI。当我在Xcode中创建一个Cocoa应用程序(我也将使用分布式对象,我认为它只在Cocoa中)时,Xcode将该项目设置为GUI应用程序。
在main函数中,我删除NSApplicationMain(...)
函数调用以从应用程序中删除GUI元素。但是,现在我无法让线程等待(侦听)来自NSDistributedNotificationCenter
的通知。该应用程序刚刚启动并立即退出。
我开始使用当前NSRunLoop
中的NSThread
,但似乎NSRunLoop
只等NSPort
秒。没有提到等待NSNotifications
。
答案 0 :(得分:4)
NSDistributedNotificationCenter
是Foundation,因此您无需创建GUI应用程序。例如,您可以创建命令行模板,并从终端运行它。作为一个非常简单的示例,您可以创建一个示例,该示例仅打印出它在下面收到的每个分布式通知。
要构建,复制到Foundation命令行应用程序的Xcode模板,或者只是复制到名为 test_note.m 的文本文件中,并根据注释进行构建。在这个例子中,应用程序永远不会结束(CFRunLoopRun()
永远不会返回),你必须通过从终端点击CTRL + C或使用类似kill
或活动监视器的方式终止它来杀死它。 / p>
// 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;
}