我很难理解如何关闭 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/