HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何等待所有NSOperations完成?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码

func testFunc(completion: (Bool) -> Void) {
    let queue = NSOperationQueue()
    queue.maxConcurrentOperationCount = 1

    for i in 1...3 {
        queue.addoperationWithBlock{
            Alamofire.request(.GET,"https://httpbin.org/get").responseJSON { response in
                switch (response.result){
                case .Failure:
                    print("error")
                    break;
                case .success:
                    print("i = \(i)")
                }
            }
        }
        //queue.addoperationAfterLast(operation)
    }
    queue.waitUntilAllOperationsAreFinished()
    print("finished")
}

输出是:

finished
i = 3
i = 1
i = 2

但我希望以下内容

i = 3
i = 1
i = 2
finished

那么,为什么queue.waitUntilAllOperationsAreFinished()不等待?

解决方法

您已添加到队列中的每个操作都会立即执行,因为Alamofire.request只是返回而不等待响应数据.

此外,那里有可能出现僵局.由于responseJSON块认在主队列中执行,因此通过调用waitUntilAllOperationsAreFinished来阻止主线程将阻止它完全执行完成块.

首先,为了解决死锁问题,您可以告诉Alamofire在不同的队列中执行完成块,其次,您可以使用dispatch_group_t对异步http请求的数量进行分组,并使主线程等待,直到所有这些请求都在小组完成执行:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)
let group = dispatch_group_create()
for i in 1...3 {
  dispatch_group_enter(group)
  Alamofire.request(.GET,"https://httpbin.org/get").responseJSON(queue: queue,options: .AllowFragments) { response in
    print(i)
    dispatch_async(dispatch_get_main_queue()) {
      // Main thread is still blocked. You can update the UI here but it will take effect after all http requests are finished.
    }
    dispatch_group_leave(group)
  }
}
dispatch_group_wait(group,DISPATCH_TIME_FOREVER)
print("finished")

大佬总结

以上是大佬教程为你收集整理的ios – 如何等待所有NSOperations完成?全部内容,希望文章能够帮你解决ios – 如何等待所有NSOperations完成?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。