Edward Hasted
Edward Hasted

Reputation: 3433

Dispatch Queues - Nesting, Optimisation & Control

Can I have your advice on the approved approach?

I have four processes that need to run sequentially:

calculateProcess1()
calculateProcess2()
calculateProcess3()
calculateProcess4()

These calculate data and update progress bars (circular) and other screen literals using dispatch queues to make the UI update.

Run them as is and lo and behold they all fire off simultaneously (what a surprise!).

How do I make the top level calls run in sequence (as above) and do I need to make changes to my DispatchQueues in the processes for updating the literals, e.g.:

DispatchQueue.main.sync { 
     let progressPercentage = (day*100/365)
     self.progressLabel.text = String(Int(progressPercentage))+"%"  
}

The initiating processes (calculateProcess1-4()) need to run from main. Should this be in ViewDidLoad, a button action or what is the most secure method?

Upvotes: 0

Views: 194

Answers (3)

Alex
Alex

Reputation: 3981

If you want to keep it simple you can provide callback blocks to your calculateProcess methods and simply nest them.

calculateProcess1() {
    calculateProcess2() {
        calculateProcess3() {
            calculateProcess4() {}
        }
    }
}

Should this be in ViewDidLoad, a button action or what is the most secure method?

viewDidLoad is probably what you want. Keep in mind if you instantiate a new viewController of the same type and show it, it will happen again, once, for that new controller as well. Also, if you are doing anything with view frames, those are not guaranteed to be laid out in viewDidLoad, but if you are simply updating text then it should be fine.

Upvotes: 2

Witek Bobrowski
Witek Bobrowski

Reputation: 4269

A one approach would be to use Operation and OperationQueue. Setting maxConcurrentOperationCount: Int to 1 on the OperationQueue, will force operations to be performed in a sequence, one after another.

(Previously called NSOperation and NSOperationQueue)

This blogpost can be helpful: https://nshipster.com/nsoperation/

And of course awesome WWDC15 session: Advanced NSOperations

Upvotes: 3

Shehata Gamal
Shehata Gamal

Reputation: 100541

1- Don't sync in main thread as it'll cause a runtime crash , it should be async

DispatchQueue.main.sync { 

2-

Should this be in ViewDidLoad, a button action or what is the most secure method?

it's up to you there is no thing related to security here , implement it as your UX

3- to run them in dequence create a custom Queue then dispatch them in it as it' ll run serially if the code inside all these methods run in the same thread of the queue meaning you don't internally dispatch inside another queue , you can also use DispatchGroup to be notified when all are done

Upvotes: 2

Related Questions