【问题标题】:NSOpenPanel on Main-Thread doesn't work主线程上的 NSOpenPanel 不起作用
【发布时间】:2018-03-06 08:17:32
【问题描述】:

我尝试在我的程序中使用NSOpenPanel,但它根本不起作用,因为 NSOpenpanel 不在主线程上运行。

这是我的代码

NSString *strURL;
NSOpenPanel *fileContents;
NSURL *panelURL;
NSArray *fileTypes = [NSArray arrayWithObjects:@"strings", @"STRINGS", nil];
fileContents = [NSOpenPanel openPanel];
[fileContents setCanChooseDirectories:NO];
[fileContents setCanChooseFiles:YES];
[fileContents setAllowedFileTypes:fileTypes];
[fileContents setAllowsMultipleSelection:NO];
NSInteger openPanelButton = [fileContents runModal];

if(openPanelButton == NSModalResponseOK)
{
    panelURL = [fileContents URL];
    strURL = panelURL.absoluteString;
}

NSArray *linesReadOnly = [strURL componentsSeparatedByString:@"\n"];

我尝试了以下两个代码:

[fileContents performSelectorOnMainThread:@selector(runModal) withObject:nil waitUntilDone:YES];

dispatch_sync(dispatch_get_main_queue(), ^{
//do UI stuff
});

在主线程上获取它根本不起作用。我做错了什么?

【问题讨论】:

  • 就 Objective-C 而言,这里已经彻底讨论了 NSOpenPanel 的主题。没有什么新鲜事。

标签: objective-c xcode multithreading macos xcode9


【解决方案1】:

您可以查看以下代码。

    //Open pannel to select any file or image and send it to server with upload file API
    let openPannel: NSOpenPanel = NSOpenPanel()
    openPannel.allowsMultipleSelection = true
    openPannel.canChooseFiles = true
    openPannel.canChooseDirectories = false
    openPannel.runModal()

    let choosenFile = openPannel.URL
    if choosenFile != nil
    {
        let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,(choosenFile?.pathExtension!)!,
                                                        nil)
        if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeImage) {
            print("This is an image!")
        }
        else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeFolder) {
            print("This is a folder!")
        }
        else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeAliasFile) {
            print("This is a zip!")
        }
        else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeSpreadsheet) {
            print("This is a sheet!")
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多