objective-c - 如何关闭 NSOpenPanel 或为什么它不自动关闭?

标签 objective-c macos cocoa nsopenpanel

我很难理解如何关闭 NSOpenPanel。它自动关闭,但它花费的时间比我希望的要长很多。

这是我的代码:

- (IBAction)startProcess:(id)sender
{

   NSString *path = [Document openVideoFile]; // open file

   // some other method calls here
}

// NSOpenPanel for file picking
+(NSString*) openVideoFile
{
   NSOpenPanel *openDialog = [NSOpenPanel openPanel];

   //set array of the file types

   NSArray *fileTypesArray = [[NSArray alloc] arrayWithObjects:@"mp4", nil];

   [openDialog setCanChooseFiles:YES];
   [openDialog setAllowedFileTypes:fileTypesArray];
   [openDialog setAllowsMultipleSelection:FALSE];

   if ([openDialog runModal] == NSFileHandlingPanelOKButton)
   {      
      NSArray *files = [openDialog URLs];

      return [[files objectAtIndex:0] path];   
   }
   else
   {
      return @"cancelled";
   }
   return nil; // shouldn't be reached
}

有趣的是,如果用户单击“取消”,面板会立即关闭,但如果用户从列表中选择一个文件,面板将保持打开状态,直到程序到达 startProcess 方法的末尾。

如果有人知道如何在用户选择文件后单击“确定”按钮后立即关闭面板,我将不胜感激!

谢谢!

最佳答案

我的猜测是,直到运行循环的后期,startProcess: 返回后,系统才真正开始移除打开的面板的动画。所以如果你的“some other method calls here”需要很长时间才能运行,那么动画开始之前需要很长时间。

理想的解决方案是在后台队列上执行缓慢的“其他方法调用”,因为您应该尽量避免阻塞主线程。但这可能需要您使目前不是线程安全的各种事物成为线程安全的,这可能很难。

另一种方法是将它们推迟到运行循环的后期:

- (IBAction)startProcess:(id)sender {
    NSString *path = [Document openVideoFile]; // open file
    dispatch_async(dispatch_get_main_queue(), ^{
       // some other method calls here
    });
}

或者您可能需要稍微推迟一下:

- (IBAction)startProcess:(id)sender {
    NSString *path = [Document openVideoFile]; // open file
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 100), dispatch_get_main_queue(), ^(void){
        // some other method calls here
    });
}

关于objective-c - 如何关闭 NSOpenPanel 或为什么它不自动关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355888/

相关文章:

ios - UIButton 的子类使用 Interface Builder 连接到父 View Controller 的 IBAction?

ios - Swift 和 Objc 的互操作性——可用性不仅仅在 objc 中起作用

macos - 安装 mongoDB(子进程失败,错误号 100 退出)

wpf - 将 WPF 移植到 Cocoa(和/或反之亦然)

objective-c - 具有全局持久存储的基于核心数据文档的应用程序

ios - NSUserDefaults 在设备和模拟器上工作,但在通过 .ipa 安装时在设备上返回 NULL

objective-c - Yahoo OAuth 与 Mac 应用程序的 gtm-oauth

Java JFrame 在 Mac OSX 上未刷新

javascript - jQuery 不能在 Chrome 中运行,但可以在 Firefox 中运行

cocoa - 将 NSString 转换为 float 会产生不精确的值