Reputation: 3433
When I press a button I start a loop of calculations and need to be able to update the main view as it progresses. As this is a background thread the screen doesn't update until the call has completed. How do I achieve this in Swift? This is my current, simplified, approach which doesn't work.
@IBAction func calculatePower(sender: AnyObject) {
for day in 1...365 {
dispatch_async(dispatch_get_main_queue()) {
self.dayLabel.text = "\(day)"
}
}
}
I typically add some 0s onto the loop otherwise it completes too quickly going from just 1 to 365.
In Cocoa I would use a statement like:
[self performSelectorOnMainThread:@selector(updateDisplayEnergySunEquator:) withObject:[NSNumber numberWithDouble:distanceFromSun] waitUntilDone:YES];
Any ideas?
Upvotes: 0
Views: 1832
Reputation: 410
@IBAction functions are called in the main thread when the button is pressed. What happens is that your closures are queued on the main thread, but your main thread is busy working on your loop. Basically, you are doing asynchronous work within one thread.
To run the loop on another thread, wrap it in a dispatch_async
and use another queue.
@IBAction func calculatePower(sender: AnyObject) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
for day in 1...365 {
dispatch_async(dispatch_get_main_queue()) {
self.dayLabel.text = "\(day)"
}
}
}
}
Upvotes: 3