gpt4 book ai didi

ios - Swift 3 多线程使用哪个队列?

转载 作者:搜寻专家 更新时间:2023-11-01 06:34:16 24 4
gpt4 key购买 nike

我正在学习斯坦福 CP 193P,正在查看 Twitter 客户端。

当网络被调用时,我假设它总是在主队列上被调用,除非在另一个队列上被调用。然而,如果不分派(dispatch)回主队列(如下所示),应用程序无法按预期工作——这意味着我们不能在主队列中。怎么办?

当获取推文时,将使用以下闭包 - 更新 UI 意味着需要在主线程 (DispatchQueue.main.async) 上完成工作

        request.fetchTweets { [weak self] (newTweets) in
DispatchQueue.main.async {
if request == self?.lastTwitterRequest {
self?.tweets.insert(newTweets, at: 0)
self?.tableView.insertSections([0], with: .fade)
}
}
}

这会调用一个便利函数,该函数被注释为“不一定在主队列上调用处理程序”。我找不到任何地方声明在哪个队列上调用它,所以我假设它在主队列上?

// convenience "fetch" for when self is a request that returns Tweet(s)
// handler is not necessarily invoked on the main queue

open func fetchTweets(_ handler: @escaping ([Tweet]) -> Void) {
fetch { results in
var tweets = [Tweet]()
var tweetArray: NSArray?
if let dictionary = results as? NSDictionary {
if let tweets = dictionary[TwitterKey.Tweets] as? NSArray {
tweetArray = tweets
} else if let tweet = Tweet(data: dictionary) {
tweets = [tweet]
}
} else if let array = results as? NSArray {
tweetArray = array
}
if tweetArray != nil {
for tweetData in tweetArray! {
if let tweet = Tweet(data: tweetData as? NSDictionary) {
tweets.append(tweet)
}
}
}
handler(tweets)
}
}

我没有写 Twitter 框架,它似乎是由斯坦福讲师编写的。

最佳答案

你问:

This calls a convenience function that is commented as "handler is not necessarily invoked on the main queue". I can't find anywhere that declares which queue it is invoked on, so I assume it is on the main queue?

不,您不能假设它在主队列中。事实上,这听起来像是在明确警告你事实并非如此。唯一可以确定它在主队列中的时间是它是否明确说明了这一点。

例如,如果底层框架正在使用 URLSession,默认情况下,它不会将主队列用于其完成处理程序。 init(configuration: delegate: delegate Queue: ) documentation警告我们 queue 参数如下:

An operation queue for scheduling the delegate calls and completion handlers. The queue should be a serial queue, in order to ensure the correct ordering of callbacks. If nil, the session creates a serial operation queue for performing all delegate method calls and completion handler calls.

并且对于给定的框架,它可能与 URLSession 队列行为完全无关。它还可能将自己的队列用于完成处理程序。

最重要的是,如果框架没有明确地向您保证闭包总是在主队列上运行,您永远不应该假设它确实如此。所以,是的,在没有任何对此效果的保证的情况下,您可能希望将任何 UI 内容分派(dispatch)到主队列并为任何模型对象执行适当的同步。


您可以,如果您有必须在特定线程上运行的代码并且您想要确保是这种情况,您可以添加一个 dispatchPrecondition 来测试它是否在主线程上。这种行为在调试版本和发布版本之间会发生变化,但这是一种快速测试它是否正在使用您认为是的队列的快速方法:

dispatchPrecondition(condition: .onQueue(.main))

关于ios - Swift 3 多线程使用哪个队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359236/

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