带有背景循环的for循环,完成?

For loop with background loop, with completion?

我想 运行 一个带有背景代码的 for loop,一旦它完成对每个项目的迭代就会发生一些事情。在没有后台代码的情况下做到这一点很简单,就像这样:

for aString: String in strings {
    if string.utf8Length < 4 {
        continue
    }

    //Some background stuff
}

//Something to do upon completion

但是在其中包含后台代码意味着在处理所有项目之前执行完成时要执行的代码。

for aString: String in strings {
    if string.utf8Length < 4 {
        continue
    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
        //Some background stuff
    }
}

//Something to do upon completion

我想知道是否可以这样做。

考虑使用调度组。这提供了一种机制,可以在分派的任务完成时通知您。所以不要使用 dispatch_async,而是使用 dispatch_group_async:

let group = dispatch_group_create();

for aString: String in strings {
    if aString.utf8Length >= 4 {
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
            //Some background stuff
        }
    }
}

dispatch_group_notify(group, dispatch_get_main_queue()) {
    // whatever you want when everything is done
}

仅供参考,这是一个相同想法的操作队列再现(虽然限制了并发操作的数量)。

let queue = NSOperationQueue()
queue.name = "String processing queue"
queue.maxConcurrentOperationCount = 12

let completionOperation = NSBlockOperation() {
    // what I'll do when everything is done
}

for aString: String in strings {
    if aString.utf8Length >= 4 {
        let operation = NSBlockOperation() {
            // some background stuff
        }
        completionOperation.addDependency(operation)
        queue.addOperation(operation)
    }
}

queue.addOperation(completionOperation)