使用 NSDistributedNotificationCenter 在 Objective-C 中开发非 GUI 用户代理
我想在 Objective-C 中创建一个用户代理,用于侦听来自默认 NSDistributedNotificationCenter
的通知。代理将没有 GUI。然而,当我在 Xcode 中创建 Cocoa 应用程序(我还将使用分布式对象,我认为这仅在 Cocoa 中)时,Xcode 将项目设置为 GUI 应用程序。
在主函数中,我删除了 NSApplicationMain(...)
函数调用,以从应用程序中删除 GUI 元素。但是,现在我无法让线程等待(侦听)来自 NSDistributedNotificationCenter
的通知。该应用程序刚刚启动并立即退出。
我研究了使用当前NSThread
中的NSRunLoop
,但是,NSRunLoop
似乎只等待NSPort
s。没有提到等待 NSNotifications
。
I would like to create a user agent in Objective-C that listens for notifications from the default NSDistributedNotificationCenter
. The agent will not have a GUI. When I create a Cocoa application (I will also be using Distributed Objects, which I think is only in Cocoa) in Xcode, however, Xcode sets the project as a GUI application.
In the main function, I remove the NSApplicationMain(...)
function call to remove the GUI elements from the application. However, now I can't get the thread to wait (listen for) notifications coming in from the NSDistributedNotificationCenter
. The app just starts and quits immediately.
I looked into using the NSRunLoop
from the current NSThread
, however, it seems that NSRunLoop
s only wait on NSPort
s. There's no mention of waiting on NSNotifications
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSDistributedNotificationCenter
是 Foundation,因此您不需要创建 GUI 应用程序。例如,您可以创建命令行模板,然后从终端运行它。作为一个非常简单的示例,您可以创建一个示例,仅打印出下面收到的每个分布式通知。要构建,请复制到 Foundation 命令行应用程序的 Xcode 模板中,或者简单地复制到名为 test_note.m 之类的文本文件中,然后根据注释进行构建。在此示例中,应用程序将永远不会结束(
CFRunLoopRun()
永远不会返回),您必须通过从终端按 CTRL+C 来终止它,或者使用kill
之类的方式终止它。 code> 或活动监视器。NSDistributedNotificationCenter
is Foundation, so you don't need to create a GUI app. You can create a command line template, for example, and run it from terminal. As a very simple example, you could create an example that just prints out every distributed notification it receives below.To build, copy into an Xcode template for a Foundation command line app, or simply copy into a text file named something like test_note.m and build according to the comments. In this example, the application will never end (
CFRunLoopRun()
never returns) and you will have to kill it by hitting CTRL+C from the terminal or killing it with something likekill
or the activity monitor.