I'm quite new to iOS Development and I'm having some issues with a Core Data fetch request. I'm using Xcode 9-beta and swift 4.
Whenever I update my database, I'm loading the new data with a fetch request, to make some calculations and fill a table view.
My challenge is that every time I do a fetch request for an entity, I'm getting the same data, even though it changed. It seems to me that is reusing the data from a previous fetch request, because if I close the app and open it again, it shows me the new stored data.
Here's my code:
if let context = container?.viewContext {
context.perform {
let request: NSFetchRequest<EntityName> = EntityName.fetchRequest()
let data = try? context.fetch(request)
self.data = data!
self.setUI()
}
}
I'm getting the container from:
let container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
I gave some generic names, as I think that's irrelevant for the question.
Any thoughts?
Thanks, JL
I got the viewContext from the container because I needed the UI thread. I guess that was my problem. I solved it passing the context I used to fetch and create the data and dispatching the request to the main queue:
func loadData(with context: NSManagedObjectContext) {
context.perform {
DispatchQueue.main.async {
let request: NSFetchRequest<EntityName> = EntityName.fetchRequest()
let data = try? context.fetch(request)
self.data = data!
self.setUI()
}
}
}
I hope it helps.