Swift: Trying to update NSTextField in a loop, but it only gets the last value

前端 未结 2 2030
孤街浪徒
孤街浪徒 2020-12-12 01:05

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 curre

相关标签:
2条回答
  • 2020-12-12 01:40

    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--
        }
    }
    
    0 讨论(0)
  • 2020-12-12 02:03

    This workt for me on 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--
        }
    }
    
    0 讨论(0)
提交回复
热议问题