Search code examples
swiftcore-datasynchronizationgrand-central-dispatchdispatch

Why is my serial dispatch not working?


I want to load some weather-data that is already stored in Core Data. Obviously I want the collection view to update itself after the data is loaded. Can somebody tell me, why this code is not working?

let context = PersistanceService.context
let fetchRequest: NSFetchRequest<Weather> = Weather.fetchRequest()
let queue = DispatchQueue(label: "loadanddisplay")
queue.sync {
    do {
        let result = try context.fetch(fetchRequest)
        self.weatherArray = result
        self.collectionView?.reloadData()

    } catch let err { print(err) }
}  

When I manually reload the Data after this function has executed, it shows up.


Solution

  • This here did the job for me:

    DispatchQueue.global(qos: .background).async {
        let context = PersistanceService.context
        let fetchRequest: NSFetchRequest<Weather> = Weather.fetchRequest()
        do {
            let result = try context.fetch(fetchRequest)
            self.weatherArray = result
        } catch let err { print(err) }
    
        DispatchQueue.main.async {
            self.pageControl.numberOfPages = self.weatherArray.count
            self.collectionView?.reloadData()
        }
    }
    

    Just make sure you call this correctly. I had to ready into how GCD works a lot to get it.