example
),但它们不会使函数等待,而是导致另一个异步块等待第一个异步块。但功能本身仍然不同步:
func myFunc() {
let group = DispatchGroup()
group.enter()
DispatchQueue.main.async {
group.leave()
}
group.notify(queue: .main) {
// Synchronized here
}
// Not synchronized here
// Function returns right away ð
}
当然有
wait
,但如果函数有可能在主线程上运行,则不能使用它。
XCTestExpectation
然而,允许轻松地等待异步调用
func myFunc() {
let expectation = XCTestExpectation()
myClass.asynchCall {
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
// Fully synchronized here
// Function returns when async call is done ð
}
如何在代码中复制类似的行为,而不是在测试中?