TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Context in environment is not connected to a persistent store coordinator: NSManagedObjectContext

Forums > Swift

Hi have this error; Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x6000006d8b60>

My DataController.swift:

import Foundation
import CoreData

class DataController: ObservableObject {
    let container: NSPersistentContainer

    init() {
        container = NSPersistentContainer(name: "History")

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

            self.container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        }
    }
}

extension DataController {
    func saveHistory(category: UUID, chatid: UUID, messages: [ChatMessage]) {
        container.performBackgroundTask { context in
            let history = Histories(context: context)
            history.id = UUID()
            history.category = category
            history.chatid = chatid
            history.messages = NSOrderedSet(array: messages)
            history.date = Date()

            do {
                try context.save()
            } catch {
                print("Failed to save history: \(error)")
            }
        }
    }
}

And my HistoryView.swift is:

import SwiftUI
import CoreData

struct HistoryView: View {
    @EnvironmentObject var DM: DataManager
    @State var contentHasScrolled = false
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(entity: Histories.entity(), sortDescriptors: []) var histories: FetchedResults<Histories>

    ...

I can't fetch history data. Maybe is empty i don't know yet.

Please anybody can help me?

3      

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.