代码之家  ›  专栏  ›  技术社区  ›  timbre timbre

如何在Swift中复制xcetestexpectation的行为

  •  0
  • timbre timbre  · 技术社区  · 6 年前

    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 😊
    }
    

    如何在代码中复制类似的行为,而不是在测试中?

    0 回复  |  直到 6 年前