停止NSApplication主事件循环 [英] Stopping the NSApplication main event loop

查看:83
本文介绍了停止NSApplication主事件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下单个 .m 文件的应用程序:

I have an application consisting of the following single .m file:

#import <Cocoa/Cocoa.h>

int main(int argc, char* argv[]) {
  [[[NSThread alloc] initWithBlock: ^{
    sleep(2);
    dispatch_async(dispatch_get_main_queue(), ^{ 
      NSLog(@"Stop");
      [[NSApplication sharedApplication] stop:nil];
    });
  }] start];
  [[NSApplication sharedApplication] run];
  NSLog(@"Run finished");
  return 0;
}

根据开发人员文档 stop 应该停止主循环( run ),但不会停止(至少在OS X 10.12和10.13上不这样).还有 终止 ,但这退出了该程序为时过早.我还尝试设置实现 applicationShouldTerminate NSApplicationDelegate ,但这从未被调用.

According to the developer documentation, stop should stop the main loop (run), but it doesn't (at least not on OS X 10.12 and 10.13). There's also terminate, but this exits the program too soon. I also tried setting an NSApplicationDelegate that implements applicationShouldTerminate, but this is never called.

如何确保(干净)退出主运行循环?

How can I make sure the main run loop is (cleanly) exited?

注意:共享应用程序主循环是必需的,因为在其他地方正在进行UI工作.更具体地说,这在转到WDE UI库中产生了问题,该库使用Cocoa提供了转到Go应用程序的窗口.

Note: The shared application main loop is necessary because there is UI work being done elsewhere. More concretely, this is giving problems in the Go WDE UI library, which uses Cocoa to provide a window to a Go application.

推荐答案

The documentation for -stop: says:

[C]从计时器或运行循环观察器例程中启用此方法不会停止运行循环,因为它们不会导致发布NSEvent对象.

[C]alling this method from a timer or run-loop observer routine would not stop the run loop because they do not result in the posting of an NSEvent object.

分派到主队列的块类似,因为它不发布事件.您可以在调用 -stop:后尝试发布 NSEventTypeApplicationDefined 事件.

A block dispatched to the main queue is similar in that it doesn't post an event. You can try posting an NSEventTypeApplicationDefined event after calling -stop:.

这篇关于停止NSApplication主事件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆