我有对象列表。每个对象都包含可选的图像值,需要下载。我想在所有图像初始化后返回列表(如果有的话)。它与NSOPerationQueues有什么关系吗?
func getFullList(list:[AnyObject], completion:(result: [AnyObject]) -> Void {
for item in list {
downloadImage(item.url), completion: {(image) in
item.image = image
)}
// I know this does not work here
completion(result: list)
}
答案 0 :(得分:1)
未经测试的代码。
func getFullList(list:[AnyObject], completion:(result: [AnyObject]) -> Void {
let group = dispatch_group_create()
for item in list {
dispatch_group_enter(group)
downloadImage(item.url), completion: {(image) in
item.image = image
dispatch_group_leave(group)
}
)}
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
completion(result: list)
}
}