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) {
}];
}];
NSBlockOperationcan't handle asynchronous operations, but it's not all that hard to create a subclass ofNSOperationthat can...Basically, you need to create an
NSOperationthat takes a block that takes another block as a completion handler. The block could be defined like this:Then, in your
NSOperationsubclass'sstartmethod, you need to call yourAsyncBlockpassing it adispatch_block_tthat will be called when it's done executing. You also need to be sure to stayKVOcompliant withNSOperation'sisFinishedandisExecutingproperties (at minimum) (see KVO-Compliant Properties in theNSOperationdocs); this is what allows theNSOperationQueueto wait until your asynchronous operation is complete.Something like this:
Note that
_executingand_finishedwill need to be defined in your subclass somewhere, and you'll need to overrideisExecutingandisFinishedproperties 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
isCancelledwhere also implemented, for example).Copied here for completeness:
AsyncBlockOperation.h:
AsyncBlockOperation.m: