【问题标题】:Obj- C Configure Run Loop for NSDistributionNotificationCenterObj-C 为 NSDistributionNotificationCenter 配置运行循环
【发布时间】:2015-10-11 10:51:47
【问题描述】:

我正在为我的辅助任务制作一个简单的 IPC 模块,

我决定使用NSDistributionNotificationCenter,因为它很简单。

但是我认为它需要在我没有的 runloop 中运行, 所以我需要创建一个RunLoop。

我在这里https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html阅读了有关 RunLoops 的文档

但是我不清楚,我应该怎么做这个RunLoop只用于接收和发送Notifications

有人能告诉我我的RunLoop 应该包括什么吗?

它应该包括一个计时器吗? 如何将消息侦听器附加到此 RunLoop 中?

很抱歉,如果我的问题有点无聊 - 我以前从未手动处理过 runloops。

我知道我必须创建一个线程并为其分配一个运行循环, 但目前尚不清楚如何添加观察者?我应该添加任何其他内容吗?

【问题讨论】:

  • 如果你没有得到更好的答案,Keith Lee 的书“Pro Objective-C”有一个非常完整的例子来说明如何做这种事情......
  • @bhaller 我根本没有任何答案 :-)

标签: objective-c multithreading macos cocoa nsrunloop


【解决方案1】:

实际上比我想象的要容易得多 我正在回答我自己的问题,以防万一将来有人在同样的事情上遇到困难,他可能会在这里找到答案,或者至少是一个kickstart。

    BOOL done = NO;

    NSDistributedNotificationCenter * notificator = [NSDistributedNotificationCenter defaultCenter];
    [notificator addObserver:self selector:@selector(gotObject:) name:@"com.ipc.test" object:nil];

    // Add your sources or timers to the run loop and do any other setup.

    do
    {
        // Start the run loop but return after each source is handled.
        SInt32    result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, YES);

        // If a source explicitly stopped the run loop, or if there are no
        // sources or timers, go ahead and exit.
        if ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished))
            done = YES;

        // Check for any other exit conditions here and set the
        // done variable as needed.
    }
    while (!done);

其实现在我找到了更简单的解决方案

        NSDistributedNotificationCenter * notificator = [NSDistributedNotificationCenter defaultCenter];
       [notificator addObserver:self selector:@selector(gotObject:) name:@"com.ipc.test" object:nil];

        CFRunLoopRun();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多