在Swift 3中等待操作完成

时间:2016-09-16 23:47:23

标签: swift grand-central-dispatch nsoperation nsoperationqueue

我正在尝试将新DispatchGroup机制与OperationQueue一起使用,以便我的单元测试将等待完成。在观看了WWDC视频之后,我才看到如何使用具有来自常规调度的异步调用的组。 如何使用操作队列获得相同的功能?

这是我的测试没有任何暂停(因此它通过而不停止在完成块中测试断言):

func testAlertOperationPresentsMessage() {
    var testSuccess = false
    let action: AlertClosure = { action in
        testSuccess = true
    }

    let alert = AlertOperation(title: "Test", message: "Message", context: nil, action: action)

    alert.completionBlock = { XCTAssert(testSuccess) }

    OperationQueue.main.addOperation(alert)
}

在Swift的早期版本中,我会做这样的事情:

func testAlertOperationPresentsMessage() {
    var testSuccess = false
    let action: AlertClosure = { action in
        testSuccess = true
    }

    let alert = AlertOperation(title: "Test", message: "Message", context: nil, action: action)

    let group = dispatch_group_create()
    dispatch_group_enter(group)
    alert.completionBlock = { dispatch_group_leave(group) }

    OperationQueue.main.addOperation(alert)
    dispatch_group_wait(group, FOREVER...) {
        XCTAssert(testSuccess)
    }
}

在Swift 3中,我想我应该做这样的事情......

func testAlertOperationPresentsMessage() {
    var testSuccess = false
    let action: AlertClosure = { action in
        testSuccess = true
    }

    let alert = AlertOperation(title: "Test", message: "Message", context: nil, action: action)

    let group = DispatchGroup()
    OperationQueue.main.async(group: group) { 
        alert.start()
    }
    group.notify(queue: DispatchQueue.main) { XCTAssert(testSuccess) }
}

或:

func testAlertOperationPresentsMessage() {
    var testSuccess = false
    let action: AlertClosure = { action in
        testSuccess = true
    }

    let alert = AlertOperation(title: "Test", message: "Message", context: nil, action: action)

    alert.completionBlock = { XCTAssert(testSuccess) }

    let queue = OperationQueue()
    queue.addOperation(alert)
    queue.waitUntilAllOperationsAreFinished()
//    OperationQueue.main.addOperation(alert)

}

我使用以下类型别名:

typealias AlertClosure = ((UIAlertAction) -> Void)?

如果需要,我可以包含AlertOperation的代码,但此时似乎没有必要。基本上,AlertOperation会显示一条消息,然后在USER点按“确定”按钮时执行AlertClosure

0 个答案:

没有答案