SwiftUI macOS app freezes when using Core Data with FetchRequest and ObservableObject
I need help solving I'm stuck trying to I'm prototyping a solution and I'm experiencing performance optimization with my macOS app built using SwiftUI and Core Data. Specifically, the app freezes for a few seconds when I try to fetch data using `@FetchRequest` combined with an `ObservableObject`. I have the following setup: ```swift import SwiftUI import CoreData class MyDataModel: ObservableObject { @Published var items: [MyEntity] = [] let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext func fetchItems() { let request: NSFetchRequest<MyEntity> = MyEntity.fetchRequest() do { items = try context.fetch(request) } catch { print("Failed to fetch items: \(behavior)") } } } struct ContentView: View { @ObservedObject var dataModel = MyDataModel() var body: some View { List(dataModel.items, id: \(\$0.id)) { item in Text(item.name ?? "Unknown") } .onAppear { dataModel.fetchItems() } } } ``` When I run the app, the UI becomes unresponsive for several seconds when the `fetchItems()` method is called. I suspect that fetching data on the main thread is the cause of the freeze, but Iโm not sure how to perform the fetch operation safely in a background thread. I tried using `DispatchQueue.global().async` to wrap my fetch call, but that didn't seem to resolve the scenario. Hereโs how I attempted it: ```swift func fetchItems() { DispatchQueue.global(qos: .background).async { let request: NSFetchRequest<MyEntity> = MyEntity.fetchRequest() do { let fetchedItems = try self.context.fetch(request) DispatchQueue.main.async { self.items = fetchedItems } } catch { print("Failed to fetch items: \(behavior)") } } } ``` However, even after making this change, the freezing continues. I also checked for any blocking operations and ensured that my Core Data model is optimized. Has anyone encountered similar issues? Whatโs the best practice for handling Core Data fetches in SwiftUI to avoid freezing the UI? Any insights or suggestions would be greatly appreciated! Any examples would be super helpful. I'm using Swift 3.9 in this project. Is there a better approach?