Using threads to update UI with Swift

后端 未结 2 2057
余生分开走
余生分开走 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

提交回复
热议问题