【问题标题】:Know when an iteration over array with async method is finished知道使用异步方法对数组的迭代何时完成
【发布时间】:2018-10-20 05:14:17
【问题描述】:

假设我有一个字符串数组,并且我调用了一个从它返回一个 int 的异步方法。我想知道我的 int 数组中什么时候有这些 int 值。

let rndStrings = ["a", "b", "c"]
var rndInts = [Int]()
rndStrings.forEach { rndString in 
   someAsyncMethod { intResult in
     rndInts.append(intResult)
   }
}

我想等到 rndInts 拥有所有 3 个值

【问题讨论】:

  • 我不确定,但是如果您想知道您的数组何时更改,您可以使用Property Observers,也许,每次您制作时都会调用更改您的数组,这意味着在初始化时也是如此!

标签: swift


【解决方案1】:

不要等待。通过DispatchGroup 获得通知。

let rndStrings = ["a", "b", "c"]
let group = DispatchGroup()
var rndInts = [Int]()
rndStrings.forEach { rndString in 
   group.enter()
   someAsyncMethod { intResult in
     rndInts.append(intResult)
     group.leave()
   }
}
group.notify(queue: DispatchQueue.main) {
   print("finished")
}

【讨论】:

  • 太棒了!有没有办法为这个组设置超时?
  • 试试wait(timeout:) 而不是notify
  • 但这会阻塞,不是吗?
  • 是的,它阻塞了当前线程。或者使用单独的DispatchTimer
猜你喜欢
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2023-03-20
  • 1970-01-01
  • 2018-02-26
相关资源
最近更新 更多