我有一个阻塞时刻。在 case .success
的 getDataByDate
中,我得到了一些数据。是数组。之后,我需要将该数组插入 callAnother
并在循环中使用数组元素。我插入 myAnotherMethod
和 completion
block 中的每个元素我想创建 arrayForDataSourceSave
并将其发送到 self?.dataSource。保存(数据:数据,添加:arrayForDataSourceSave
每次我的 add
都是空的。如何解决这个问题?
private func callAnother(data: [AnyModel], completion: @escaping () -> Void) {
var arrayForDataSourceSave: []()
for element in data {
guard let id = element.id else { return }
APIService.myAnotherMethod(id: id, completion: { result in
switch result {
case .success(let well):
arrayForDataSourceSave.append(well)
print(well)
case .error(let error):
print("request error: \(error)")
}
})
}
completion()
}
func refresh(completion: @escaping () -> Void) {
APIService.getDataByDate(date: date, completion: { [weak self] (result) in
switch result {
case .success(let data):
self?.callAnother(data: data, completion: {
self?.dataSource.save(data: data, add: arrayForDataSourceSave)
})
case .error(let error):
print("request error: \(error)")
}
completion()
})
}
我通过 DispatchGroup
找到了该任务的决定,并且我的代码运行良好:
private func callAnother(data: [AnyModel]) {
let dispatchGroup = DispatchGroup()
var arrayForDataSourceSave = [AnyModel]()
for element in data {
guard let id = element.id else { return }
dispatchGroup.enter()
APIService.myAnotherMethod(id: id, completion: { result in
switch result {
case .success(let well):
arrayForDataSourceSave.append(well)
print(well)
case .error(let error):
print("request error: \(error)")
}
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: DispatchQueue.main) {
self?.dataSource.save(data: data, add: arrayForDataSourceSave)
}
}
func refresh(completion: @escaping () -> Void) {
APIService.getDataByDate(date: date, completion: { [weak self] (result) in
switch result {
case .success(let data):
self?.callAnother(data: data)
case .error(let error):
print("request error: \(error)")
}
completion()
})
}
关于ios - 如何将实际数据从一个闭包获取到另一个闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710360/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |