对于带背景循环的循环,完成?

时间:2015-02-21 18:36:52

标签: ios objective-c swift for-loop dispatch-async

我想用背景代码运行一个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

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

1 个答案:

答案 0 :(得分:4)

考虑使用调度组。这提供了一种机制,可在分派的任务完成时通知您。因此,而不是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)