Using threads to update UI with Swift

后端 未结 2 1963
余生分开走
余生分开走 2021-02-05 08:48

I\'m developing a software with Xcode 6 using Swift. When I press a button, my code takes some informations from the web and writes them on my NSWindow.

So imagine some

相关标签:
2条回答
  • 2021-02-05 09:06

    There is GCD. Here is a basic usage:

    for page in listOfPages {
        var label = NSTextField()
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let result = getInformationFromPage(page)
            dispatch_async(dispatch_get_main_queue()) {
                label.stringValue = result
            }
        }
    }
    

    dispatch_async function asynchronously runs the block of code on the given queue. In first dispatch_async call we dispatch the code to run on background queue. After we get result we update label on main queue with that result

    0 讨论(0)
  • 2021-02-05 09:19

    Swift 3.0 + version

    DispatchQueue.main.async() {
        // your UI update code
    }
    

    Posted this because XCode cannot suggest the correct syntax from swift 2.0 version

    0 讨论(0)
提交回复
热议问题