简体   繁体   中英

Updating UIProgressView Progress from background thread

I'm using a UIProgressView and it uses the observedProgress property. I then have a variable of type Progress that is observed.

Now I'm writing to Core Data on a background thread and then updating the completedUnitCount but it's crashing.

Here's the code:

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
                }
            }
        }
    }
}

So it's crashing on line self.downloadProgress.completedUnitCont = Int64(index + 1) . I realise in writing this that I should also be using weak or unowned self to stop retain cycles, but are there other issues?

All the UI related code have to be performed from the main thread, so you have to dispatch call self.downloadProgress.completedUnitCont = Int64(index + 1) to main thread. Something like this:

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

Apple Says:

Updating UI on a thread other than the main thread is a common mistake that can result in missed UI updates, visual defects, data corruptions, and crashes.

So whenever you are performing any task on background thread and need to make any ui updates in the process, use all those code inside the following block.

DispatchQueue.main.async{ <uiupdate code here> }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM