从后台线程更新 UIProgressView 进度

Mr.*_*r.P 3 core-data ios swift

我正在使用 aUIProgressView并且它使用该observedProgress属性。然后我有一个Progress被观察到的类型变量。

现在我正在后台线程上写入核心数据,然后更新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
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mis*_*ewb 5

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

DispatchQueue.main.async {
  self.downloadProgress.completedUnitCont = Int64(index + 1)
}
Run Code Online (Sandbox Code Playgroud)