0

Here is my @FetchRequest for User entity:

struct SettingsView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(
        entity: User.entity(),
        sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)]
      ) var items: FetchedResults<User>

    var body: some View {
        List(items, id: \.self) { user in
            Text("\(user.name)")
        }
    }
}

it should fetch all user entities, but returns exactly 0. Why?

How do I pass that context?

struct Taboo: App {
    @StateObject private var coreDataStack = CoreDataStack.shared
    var body: some Scene {
        WindowGroup {
            SettingsView()
                .environment(\.managedObjectContext, coreDataStack.persistentContainer.viewContext)
        }
    }
}

There is no error during setup my core data model. So where might be the issue?

class CoreDataStack: ObservableObject {
    static let shared = CoreDataStack()
    
    lazy var persistentContainer: NSPersistentContainer = {
        
        let container = NSPersistentContainer(name: "Taboo")
        

        container.loadPersistentStores { _, error in
            if let error {
                fatalError("Failed to load persistent stores: \(error.localizedDescription)")
            }
        }
        return container
    }()
        
    private init() { }
}

PS There is a lot of entities of User because I am switching from using MagicalRecord to SwiftUI approach.

2
  • 1
    IDK anything about magical record but if I took a wild guess the URL they are using is likely not the default URL. You would have to find out from MagicRecord where the actual database it is load the proper store URL. Commented Apr 1 at 13:34
  • 1
    Wow, it was very fantastic answer. I could never find it without you. Indeed, I had to find where it is located and finally found it. Commented Apr 1 at 19:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.