0
votes

I just read long introduction to NSOperationQueues and NSOperation here.

My question is the following. I need to run two operations is the same time. When both those tasks finished I need to make another calculations based on results from two finished operations. If one of the operations fails then whole operation should also fails. Those two operations does not have dependencies and are completely independent from each other so we can run them in parallel.

How to wait for this 2 operation to finish and then continue with calculations? I don't want to block UI Thread. Should I make another NSOperation that main method is creating two NSOperations add them to some local (for this operation) queue and wait with waitUntilAllOperationsAreFinished method. Then continue calculations?

I don't like in this approach that I need to create local queue every time I creating new operation. Can I design it that way that I can reuse one queue but wait only for two local operations? I can imagine that method waitUntilAllOperationsAreFinished can wait until all tasks are done so it will blocks when a lot of tasks will be performed in parallel. Any design advice? Is creating NSOperationQueue expensive? Is there any better ways to do it in iOS without using NSOperation & NSOperationQueue? I'm targeting iOS 9+ devices.

1
Don't wait. Use a DispatchGroup and notify You may not even need NSOperation; it may be sufficient just to dispatch two functions on a concurrent queuePaulw11
This matches what @Paulw11 wrote about: stackoverflow.com/questions/41412780/…CodeBender
Looks like it is designed for my problem. I just can't find any example in the internet that reuse some calculated objects from individual tasks in notify block. Every example is based on print() something without exchanging data. Thank You guys for point my attention to this. I was not aware of DispatchGroup at all.Marcin Kapusta

1 Answers

0
votes

In Swift 4, you can do it this way:

let group = DispatchGroup()
// async
DispatchQueue.global().async {
    // enter the group
    group.enter()
    taskA(onCompletion: { (_) in
        // leave the group
        group.leave()
    })
    group.enter()
    taskB(onCompletion: { (_) in
        group.leave()
    })
}

group.notify(queue: DispatchQueue.main) {
    // do something on task A & B completion
}

And there is an excellent tutorial on GCD from raywenderlich.com.