Search code examples
objective-cmultithreadingnsblockoperation

Grouping NSOperation working on same object and detect when they have finished in iOS


I have an iOS app where 5 NSBlockOperation produce an NSArray of objects each and add it to a shared synchronized NSMutableArray which serves as a UITableView datasource.

The operation are independent from each other, and as soon as they have finished I need to launch a UITableView data reload.

Unfortunately I couldn't find a way to do this with NSOperation. Do I need to use another multi thread design ?


Solution

  • Add your reload data call to yet another NSOperation, which has as its dependencies (see addDependency:) the other five operations. It will then not be executed until the others are complete.

    Be sure to wrap your UI calls in a GCD dispatch to the main thread.

    From the NSOperation reference:

    Dependencies are a convenient way to execute operations in a specific order. You can add and remove dependencies for an operation using the addDependency: and removeDependency: methods. By default, an operation object that has dependencies is not considered ready until all of its dependent operation objects have finished executing. Once the last dependent operation finishes, however, the operation object becomes ready and able to execute.