Swift:试图在循环中更新NSTextField,但它只获取最后一个值 [英] Swift: Trying to update NSTextField in a loop, but it only gets the last value

查看:247
本文介绍了Swift:试图在循环中更新NSTextField,但它只获取最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的简单程序是循环通过数组导出几个文件。
当它在循环中时,我想更新一个文本字段,告诉用户当前正在导出哪个文件。
代码看起来像这样:

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

会发生什么: code> println 可正常工作,为每个文件抛出一个消息,但名为 fileNameExportLabel 的标签仅在最后一个文件因此在整个循环中为空,并在循环到达结束时获取最后一个文件名。

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.

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

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.

提前感谢!

推荐答案

您的循环正在主线程上运行。 UI更新不会发生,直到你的函数完成。因为这需要很长时间,你应该在后台线程上执行此操作,然后更新主线程上的文本框。

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.

尝试:

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:试图在循环中更新NSTextField,但它只获取最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆