【问题标题】:Setting main queue as underlying queue for NSOperationQueue将主队列设置为 NSOperationQueue 的底层队列
【发布时间】:2016-08-21 20:58:06
【问题描述】:

NSOperationQueue 类有一个underlyingQueue 属性,用于设置将在其上执行NSOperation 实例的调度队列。

let dispatchQueue = dispatch_queue_create("custom.queue", DISPATCH_QUEUE_SERIAL)
let opQueue = NSOperationQueue()
opQueue.underlyingQueue = dispatchQueue

但是,官方文档指出:

该属性的值不能是dispatch_get_main_queue返回的值

Apple 似乎没有对这个主题做出更多解释。但是,将主队列用作underlyingQueue 不会引发任何错误,也不会产生任何不需要的行为。这背后的原因是什么?

【问题讨论】:

  • 如果要使用主队列,为什么要调用dispatch_queue_create?只需使用dispatch_get_main_queue
  • dispatch_queue_create 仅用作如何设置underlyingQueue 属性的示例。正如您从文档中看到的那样,dispatch_get_main_queue 不应用作底层队列。

标签: ios swift nsoperation nsoperationqueue


【解决方案1】:

可能有多种原因;可能会出现死锁,但您需要向 Apple 询问明确的答案。

如果您的整个操作必须在主队列上执行,那么您可以使用NSOperationQueue.mainQueue 获取与主线程关联的操作队列。如果只有部分操作需要在主队列上执行(例如更新 UI 元素),那么您可以根据需要将该操作同步或异步分派到主队列上。

【讨论】:

    猜你喜欢
    • 2012-06-12
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多