i need to put asynchronous operations into an operation queue, however, they need to execute on after the other
self.operationQueue = [NSOperationQueue new];
self.operationQueue.maxConcurrentOperationCount = 1;
[self.operationQueue addOperationWithBlock:^{
// this is asynchronous
[peripheral1 connectWithCompletion:^(NSError *error) {
}];
}];
[self.operationQueue addOperationWithBlock:^{
// this is asynchronous
[peripheral2 connectWithCompletion:^(NSError *error) {
}];
}];
the problem is, since peripheralN connectWithCompletion is asynchronous, the operation in queue is ended and the next is executed, i would need however simulate, that peripheralN connectWithCompletion is synchronous and wait with the end of operation, till the asynchronous block executes
so i would need a behaviour like this, only using the operation queue
[peripheral1 connectWithCompletion:^(NSError *error) {
[peripheral2 connectWithCompletion:^(NSError *error) {
}];
}];
NSBlockOperation
can't handle asynchronous operations, but it's not all that hard to create a subclass ofNSOperation
that can...Basically, you need to create an
NSOperation
that takes a block that takes another block as a completion handler. The block could be defined like this:Then, in your
NSOperation
subclass'sstart
method, you need to call yourAsyncBlock
passing it adispatch_block_t
that will be called when it's done executing. You also need to be sure to stayKVO
compliant withNSOperation
'sisFinished
andisExecuting
properties (at minimum) (see KVO-Compliant Properties in theNSOperation
docs); this is what allows theNSOperationQueue
to wait until your asynchronous operation is complete.Something like this:
Note that
_executing
and_finished
will need to be defined in your subclass somewhere, and you'll need to overrideisExecuting
andisFinished
properties to return the correct values.If you put all that together, along with an initializer that takes your
AsyncBlock
, then you can add your operations to the queue like this:I put together a gist of a simple version of this here: AsyncOperationBlock. It's only a minimum implementation, but it should work (it would be nice if
isCancelled
where also implemented, for example).Copied here for completeness:
AsyncBlockOperation.h:
AsyncBlockOperation.m:
What I did was playing with
[myQueue setSuspended:YES]
and[myQueue setSuspended:NO]
before and after respectively.For example:
The achieved effect is that the queue is suspended before the async task, therefore even though the operation block is returned, it only starts the next operation (subject to
maxConcurrentOperationCount
of course) when the async task's completion block is called.