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 something like this:
@IBAction func buttonPressed(sender: AnyObject) { for page in listOfPages //Number of pages is 40. { var label: NSTextField = NSTextField(); label.stringValue = getInformetionsFromPage(page) /* some code to add label in the window here */ } }
The problem is that once I click the button, it takes a while before I see the list of results, in the main time the app is frozen. That's because I'm not using any threads to handle this problem. How could I implement threads to see every label updated every step of the loop? I'm new with threads and Swift, so I would need some help!
Thank you guys.
1) Have each thread set a "DataUpdated" flag when new data is available, and have the UI periodically check for new data. 2) Create each thread with a callback to a UI Update(...) method to be called when new data becomes available.
In all cases, your app should only update UI objects on the main thread. This means that you should craft a negotiation policy that allows multiple threads to communicate work back to the main thread, which tasks the topmost activity or fragment with the work of updating the actual UI object.
If you're on a background thread and want to execute code on the main thread, you need to call async() again. This time, however, you do it on DispatchQueue. main , which is the main thread, rather than one of the global quality of service queues.
The main thread is the one that starts our program, and it's also the one where all our UI work must happen. However, there is also a main queue, and although sometimes we use the terms “main thread” and “main queue” interchangeably, they aren't quite the same thing.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With