Aaron Vegh
Aaron Vegh

Reputation: 5217

Adding a "Final" NSOperation to a Queue with Undetermined Number of Operations

I'm using AFNetworking as my network stack to communicate with a web service and populate a local data store. During synchronization runs, I have an array of API endpoints to run through, and when that run is complete, I add a final operation, which takes the resulting JSON to fill up the database.

The problem I'm having is that the result of some of those JSON-fetching operations requires me to call other endpoints, and now I don't know when I should add that "Final" operation.

The way I have things working now, I have a series of primary operations, and then add the "final" operation. During that time, the primaries have returned and caused me to create secondary operations, like so:

* Primary Fetch Operation A
* Primary Fetch Operation B
* Final Operation
* Secondary Fetch Operation B1

I need to figure out how to ensure that "Final Operation" is always going to run last.

One thing I've tried is adding an observer to the operation queue's operationCount property, but it seems that it can run down to 0 before a secondary operation is added.

Upvotes: 2

Views: 125

Answers (1)

David Rodrigues
David Rodrigues

Reputation: 842

Unfortunately I believe the observer won't work, AFNetworking invokes callbacks from the completionBlock of NSOperation and this means that the operation is already finished and removed from the queue, which explains why you have reached a operationCount of 0 before submit the secondary operation.

You could use a dispatch_group_t to accomplish this, before scheduling an operation (primary or secondary) you enter the group (dispatch_group_enter) and then when the operation completes you leave the group (dispatch_group_leave). If the finished operation requires a secondary operation before leaving the group follow the same pattern, enter the group again and schedule the secondary operation. Finally you will be notified (dispatch_group_notify) when all the operations have completed making the perfect time to schedule the final operation.

Upvotes: 4

Related Questions