简体   繁体   中英

How to delay loop in for loop till notified in Swift?

I need to perform several time consuming operations. Each one includes large mathematical calculations and GMS objects creation and takes 10s aprox. It uses notifications at several places.

I have parameters for each operation in a dictionary and I tried to use simple for loop to perform operations one by one but calculations are not sequenced properly. The number of calculations may differ so I need some loop to go through the dictionary.

I am thinking about waiting in loop until notified to perform next loop. I know where to post notification but cant find any solution how to observe it in a for loop. Is it correct approach and if so how to do it?

Any suggestions?

Edit1: Example:

For calculation in calculationsDict {
       performCalculation(calc: calculation) // runs 10s in different threads
}

How to delay second and any subsequent performCalculation to the moment where each performCalculation is completely finished?

Edit2: performCalculation has nested functions, it sends notifications to initiate other actions, and all actions together have hundreds lines of code and at the end there are many objects in the mapview as a result. What I need is to repeat that whole bunch of actions(here referred to as performCalcultion()) but just right when the previous one is completed completely.

Edit3: What I ask for is how to make one performCalculation() having completion handler for next performCalculation().

Your performCalculation(calc:) method definitely needs a completion closure parameter for us to know when the calculations for a given input are done. Let's say it now looks like this and you execute the completion when all of your inner asynchronous tasks are finished:

func performCalculation(calc: ..., completion: @escaping () -> Void) {
    // Call when all done
    completion()
}

I would then suggest implementing a method that will recursively call itself and pass the needed dict to the method above:

func performAllCalculations(with calculationsDict: ...) {
    guard calculationsDict.count > 0, let calculation = calculationsDict.first else {
        // Terminate recursion when the dict is empty
        return
    }
    // Calculate with the first item from the dict
    performCalculation(calc: calculation) { [weak self] in
        // Calculation is done
        // Call the main method again without the first item in the dict
        self?.performAllCalculations(with: calculationsDict.dropFirst())
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM