如何等待所有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分组asynchronousHTTP请求的数量,并保持主线程等待,直到所有这些请求在组完成执行:

 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") 

我build议你使用KVO,并观察队列何时完成所有的任务,而不是阻塞当前的线程,直到所有的操作完成。 或者你可以使用依赖关系。 看看这个 SO问题