![](/img/trans.png)
[英]UIProgressView progress not updating even when run in the main thread
[英]Updating UIProgressView Progress from background thread
我正在使用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)
崩潰。 我在寫這篇文章時意識到,我也應該使用weak
或unowned
自我來停止保留周期,但是還有其他問題嗎?
所有與UI相關的代碼都必須從主線程執行,因此您必須將調用self.downloadProgress.completedUnitCont = Int64(index + 1)
調度到主線程。 像這樣:
DispatchQueue.main.async {
self.downloadProgress.completedUnitCont = Int64(index + 1)
}
蘋果說:
在除主線程之外的其他線程上更新UI是一個常見錯誤,可能會導致錯過UI更新,視覺缺陷,數據損壞和崩潰。
因此,每當您在后台線程上執行任何任務並且需要在進程中進行任何ui更新時,請在以下代碼塊中使用所有這些代碼。
DispatchQueue.main.async{ <uiupdate code here> }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.