NSMenu动画阻止主线程

ten*_*ire 7 nonblocking nsmenu nsview nsthread

我有:

  • NSStatusItem具有自定义视图(在辅助线程中滚动文本),辅助线程更新内部状态并通过setNeedsDisplay通知主线程.
  • 在mouseDown上,弹出一个NSMenu.
  • 但是,如果选择了NSMenu中的任何NSMenuItem,或者如果检测到第二个mouseDown并且NSMenu消失,则滚动文本动画会断断续续.

似乎NSMenu默认视图在执行动画时会阻塞主线程.我已经通过辅助线程输出time_since_last_loop与视图的drawRect:(主线程)进行了测试,只有drawRect显示了断断续续.自定义视图的drawRect从~30 fps下降到5帧几帧.

有没有NSMenu动画非阻塞,或与自定义视图的drawRect并发的方法?

Kei*_*ber 0

我使用 NSTimer 和 NSEventTrackingRunLoopMode 来解决类似的问题。

在你的主线程中,创建一个计时器:

    updateTimer = [[NSTimer scheduledTimerWithTimeInterval:kSecondsPerFrame target:self selector:@selector(update:) userInfo:nil repeats:YES] retain];

   // kpk important: this allows UI to draw while dragging the mouse.
   // Adding NSModalPanelRunLoopMode is too risky.
    [[NSRunLoop mainRunLoop] addTimer:updateTimer forMode:NSEventTrackingRunLoopMode];
Run Code Online (Sandbox Code Playgroud)

然后在你的 update: 例程中,检查 NSEventTrackingRunLoopMode:

   // only allow status updates and drawing (NO show data changes) if App is in
   // a Modal loop, such as NSEventTrackingRunLoopMode
   NSString *runLoopMode = [[NSRunLoop currentRunLoop] currentMode];
   if ( runLoopMode == NSEventTrackingRunLoopMode )
   {
       ... do periodic update tasks that are safe to do while
       ... in this mode
       ... I *think* NSMenu is just a window
       for ( NSWindow *win in [NSApp windows] )
       {
          [win displayIfNeeded];
       }

       return;
   }

   // do all other updates
   ...
Run Code Online (Sandbox Code Playgroud)