How to use coreData on a background thread with SwiftUI

Viewed 272

I am using CoreData with SwiftUI. I'm having some performance issues and I guess it's loading lot's of objects on the viewContext in the main thread. I was wondering what is the best way around this?
Prior to SwiftUI I was using:

lazy var privateContext: NSManagedObjectContext = {
    
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    
    managedObjectContext.persistentStoreCoordinator = self.persistentContainer.persistentStoreCoordinator
        
    return managedObjectContext
    
}()

And I would use it in:

self.privateContext.perform({ ...

This worked quite well and I wanted to implement a similar approach in SwiftUI. I'm using the default coreData template with a PersistenceController Struct.

I can get the viewContext and inject using:

.environment(\.managedObjectContext, persistenceController.container.viewContext) 

I thought to do something like:

.environment(\.managedObjectContext, persistenceController.container.newBackgroundContext()) 

But not sure what is the best practice? I am using a fetchRequest in the init for my View:

@FetchRequest var items: FetchedResults<Item>

init() {
    
    let request = NSFetchRequest<Item>(entityName: "Item")
    request.sortDescriptors = [NSSortDescriptor(key: "createdAt_", ascending: true)]
    _items = FetchRequest(fetchRequest: request)

}
0 Answers
Related