objective-c - 使用 NSDistributedNotificationCenter 在 Objective-C 中开发非 GUI 用户代理

标签 objective-c xcode multithreading daemon nsnotifications

我想在 Objective-C 中创建一个用户代理,用于监听来自默认 NSDistributedNotificationCenter 的通知。代理将没有 GUI。然而,当我在 Xcode 中创建 Cocoa 应用程序(我还将使用分布式对象,我认为这仅在 Cocoa 中)时,Xcode 将项目设置为 GUI 应用程序。

在主函数中,我删除了 NSApplicationMain(...) 函数调用,以从应用程序中删除 GUI 元素。但是,现在我无法让线程等待(监听)来自 NSDistributedNotificationCenter 的通知。该应用程序刚刚启动并立即退出。

我研究了使用当前NSThread中的NSRunLoop,但是,NSRunLoop似乎只等待NSPorts。没有提到等待 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/

相关文章:

ios - IOS 的 getFromLocationName() 的替代品是什么?

ios - UIView:如何使宽度在另一个图像之前自动结束?

python - sudo pip install pil 在 Mac 10.9.1 上出错

objective-c - 'willRotateToInterfaceOrientation' 不适用于我的 DetailViewController

iphone - Storyboard中制作的 UIScrollView 的帧值为零

php - 使用 JSONmodel 尝试从服务器获取数据到 ios 设备

java - threadDefaultFactory 中的 AtomicInteger

c++ - 使用 Qt/C++ 从单独的线程发出对象时如何避免复制?

java - 为什么 ThreadPoolExecutor$Worker 扩展 AbstractQueuedSynchronizer

ios - 按钮上的标签,如何在 iOS7 中突出显示按下按钮时的文本?