gpt4 book ai didi

swift - (XCTestCase) 如何断言 block 是否已在主线程或外部(任何其他线程)调用?

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:45 25 4
gpt4 key购买 nike

如果在主线程或外部(任何其他线程)调用了一个 block ,如何断言?假设我们有一个类:

class A {
func asyncOperation(handler: Void -> Void) {
//some processing
dispatch_async(dispatch_get_main_queue(), completionHandler)
}
}

class ATests: XCTestCase {
func testHandlerInMainThread(){
let a = A()
let expectation = expectationWithDescription("Handler must be called in main thread")

a.asyncOperation{
// how to get current_queue ?
XCTAssertEqual( current_queue, dispatch_get_main_queue())
expectation.fulfill()
}
waitForExpectationsWithTimeout(3, handler: nil)
}

最佳答案

您可以使用 NSThread 的类方法 isMainThread 如果当前线程是主线程,它返回 true

如果你想测试一个特定的队列是否真的是你的代码执行的队列,你可以测试队列的“标签”:

 dispatch_queue_t
dispatch_queue_create(const char *label, dispatch_queue_attr_t attr);

const char *
dispatch_queue_get_label(dispatch_queue_t queue);

后者在单元测试中更有用,而不是用于实际代码。您不应该使用这种方法来确定您的代码是否可能死锁,因为这是不够的!

编辑:

为了获取当前队列的标签(在Swift中):

let label : String? = String.fromCString(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))

关于swift - (XCTestCase) 如何断言 block 是否已在主线程或外部(任何其他线程)调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31326263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com