search

Home  >  Q&A  >  body text

objective-c - NSOperationQueue中如何实现按顺序单个执行

我发现maxConcurrentOperationCount=1并不管用 虽然网上搜到一大堆说添加依赖能解决问题 但现实中有如下api

CMStepCounter ios8苹果计步器

都是异步回调的

怎么实现如下功能

for(int i = 0; i< 24 ;i ++)
{
[_stepCounter queryStepCountStartingFrom:fromDate

           to:toDate                                                    
           toQueue:_timeQueue
           withHandler:^(NSInteger numberOfSteps, NSError *error)
     {

     }

}

按顺序取出

ringa_leeringa_lee2763 days ago471

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-04-27 09:05:07

    maxConcurrentOperationCount will definitely work. One-step interface serialization, you have to send the time (condition variable, signal, etc.) after receiving the callback

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-27 09:05:07

    maxConcurrentOperationCount=1只能保证一次只有一个operation在执行,但并不能够保证将所有加入的operation严格按序执行。
    如果需要让加入的所有operation都严格按序执行的话,最简单的方法就是每次给加入的operationAdd dependency.
    Similar to this:

    NSOperation *operationToAdd;
    NSOperation *lastOperation = queue.operations.lastObject;
    if (lastOperation) {
        [operationToAdd addDependency:lastOperation];
    }
    [queue addOperation:operationToAdd];

    As far as the question in your question is concerned, although the final callbacks of the two functions you gave are asynchronous, it does not mean that they cannot be implemented using operation.

    You can subclass a NSOperation yourself, perform an asynchronous operation and end it NSOperation,执行异步操作然后在回调里面把operation结束掉。
    这样一个异步的调用就转成了一个operationin ​​the callback.

    Such an asynchronous call is converted into a 🎜, and the above method of adding dependencies can also be applied to achieve strict sequential execution. 🎜

    reply
    0
  • Cancelreply