gpt4 book ai didi

ios - 从后台线程更新 UIProgressView 进度

转载 作者:可可西里 更新时间:2023-11-01 00:39:12 25 4
gpt4 key购买 nike

我正在使用 UIProgressView,它使用 observedProgress 属性。然后我有一个观察到的 Progress 类型的变量。

现在我正在后台线程上写入 Core Data,然后更新 completedUnitCount 但它崩溃了。

代码如下:

var downloadProgress: Progress

init() {
downloadProgress = Progress()
}

func saveStuff() {
let stuff: [[String: Any]] = //some array of dictionaries

downloadProgress.totalUnitCount = Int64(stuff.count)

persistentContainer.performBackgroundTask { (context) in
for (index, item) in stuff.enumerated() {
// create items to be saved
context.perform {
do {
try context.save()
self.downloadProgress.completedUnitCont = Int64(index + 1)
} catch {
// handle error
}
}
}
}
}

所以它在 self.downloadProgress.completedUnitCont = Int64(index + 1) 行崩溃了。我在写这篇文章时意识到我还应该使用 weakunowned self 来停止保留周期,但是还有其他问题吗?

最佳答案

所有与 UI 相关的代码都必须从主线程执行,因此您必须将调用 self.downloadProgress.completedUnitCont = Int64(index + 1) 分派(dispatch)到主线程。像这样:

DispatchQueue.main.async {
self.downloadProgress.completedUnitCont = Int64(index + 1)
}

关于ios - 从后台线程更新 UIProgressView 进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49918267/

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