Swift:尝试在循环中更新NSTextField,但是它只获取最后一个值



我的非常简单的程序正在循环遍历数组以导出几个文件。当它处于循环中时,我希望它更新一个文本字段,以告诉用户当前正在导出哪个文件。代码如下所示:

for item in filesArray {
    var fileName = item["fileName"]
    fileNameExportLabel.stringValue = "Exporting (fileName).ext"
    println("Exporting (fileName).ext")
    //--code to save the stuff goes here--
}

发生的事情是:println工作正常,为每个文件抛出一条消息,但是称为fileNameExportLabel的标签仅在导出最后一个文件时更新,因此在整个循环期间它是空白的,并在循环结束时获得最后一个文件名。

任何想法?我在这里是一个完全的新手,我想知道NSTextField是否需要一个命令来更新,类似于表视图。

提前感谢!

你的循环在主线程上运行。在函数完成之前,UI更新不会发生。因为这需要很长时间,你应该在后台线程上做这个,然后在主线程上更新文本字段。

试试这个:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    for item in filesArray {
        var fileName = item["fileName"]
        // Update the text field on the main queue
        dispatch_async(dispatch_get_main_queue()) {
            fileNameExportLabel.stringValue = "Exporting (fileName).ext"
        }
        println("Exporting (fileName).ext")
        //--code to save the stuff goes here--
    }
}

这在Swift 4上为我工作

DispatchQueue.global(qos: .default).async {
    for item in filesArray {
        var fileName = item["fileName"]
        // Update the text field on the main queue
        DispatchQueue.main.async {
            fileNameExportLabel.stringValue = "Exporting (fileName).ext"
        }
        print("Exporting (fileName).ext")
        //--code to save the stuff goes here--
    }
}

最新更新