ios - 如何将实际数据从一个闭包获取到另一个闭包?
<p><p>我有一个阻塞时刻。在 <code>case .success</code> 的 <code>getDataByDate</code> 中,我得到了一些数据。是数组。之后,我需要将该数组插入 <code>callAnother</code> 并在循环中使用数组元素。我插入 <code>myAnotherMethod</code> 和 <code>completion</code>block 中的每个元素我想创建 <code>arrayForDataSourceSave</code> 并将其发送到 <code>self?.dataSource。保存(数据:数据,添加:arrayForDataSourceSave</code></p>
<p>每次我的 <code>add</code> 都是空的。如何解决这个问题?</p>
<pre><code>private func callAnother(data: , 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: { (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()
})
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我通过 <code>DispatchGroup</code> 找到了该任务的决定,并且我的代码运行良好:</p>
<pre><code>private func callAnother(data: ) {
let dispatchGroup = DispatchGroup()
var arrayForDataSourceSave = ()
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: { (result) in
switch result {
case .success(let data):
self?.callAnother(data: data)
case .error(let error):
print("request error: \(error)")
}
completion()
})
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何将实际数据从一个闭包获取到另一个闭包?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/47710360/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/47710360/
</a>
</p>
页:
[1]