Swift: Trying to update NSTextField in a loop, but

2019-08-12 07:47发布

问题:

My very simple program is looping through an array to export several files. While it's in the loop, I'd like it to update a text field to tell the user which file is currently exporting. Code looks like this:

for item in filesArray {
    var fileName = item["fileName"]

    fileNameExportLabel.stringValue = "Exporting \(fileName).ext"
    println("Exporting \(fileName).ext")

    //--code to save the stuff goes here--
}

What happens is: println works correctly, throwing out a message for each file, but the label called fileNameExportLabel is only updated when the last file has been exported, so it's blank during the whole loop and gets the last file name once the loop reaches the end.

Any Idea? I'm a total noob here, I'm wondering if the NSTextField needs a command to be updated, similarly to a table view.

Thanks in advance!

回答1:

Your loop is running on the main thread. The UI updates won't happen until your function finishes. Since this is taking a long time, you should do this on a background thread and then update the textfield on the main thread.

Try this:

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--
    }
}