-waitUntilAllOperationsAreFinished
The Problem
Unbounded problems aren’t easy to resolve because most SDKs and toolkits are designed to resolve one-off problems, for example:
List the contents of this directory, then when you’re done give me a call.
If you’re dealing with local resources, you’ll almost always use a synchronous method that smells pretty procedural (like NSFileManager). No trouble to be had there. :)
If the resource is laggy, far away, or otherwise generally not ideal for synchronous access, it’s almost granted that you’ll spin up an object, set its delegate to your object (that lives longer), then call some method (which returns void), and wait for the object to call some method (thru delegation) on your object (like NSURLConnection).
This, then, is more challenging:
Recursively list the contents of this directory, and when you’re all done, give me a call.
The approach used to resolve the first problem is going to leave a mess, because for every subdirectory there’s going to be one more delegate call, and there’s usually no way to know if the last invocation was the last one.
If another bunch of stuff needs to be done only after the unbounded operation has finished, then things are going to be even messier. But a private NSOperationQueue makes it easily managable.
Interim Solution
My first attempt at this problem uses a private NSOperationQueue:
- Create a
NSOperationQueue, then set its max number of concurrent operations to 1. - Create a generator that can be called multiple times, with each invocation scheduling a new concurrent
NSOperationon the queue. - Make sure the scheduled operation calls its generator to schedule more work before the operation finishes.
- Suspend the queue, then call
-waitUntilAllOperationsAreFinishedand resume the queue.
If you prefer not blocking up the main thread, try doing the magic on another operation queue. For example, schedule an NSBlockOperation that only waits for the private queue to be emptied, and cleans it up thereafter. ;)