Home > OS >  Having trouble adding values to core data outside of a View
Having trouble adding values to core data outside of a View

Time:01-09

I'm trying to load data into a CoreData entity "Articles" from a function I would like to call in an init() {} call when my app starts which means I'm not doing this from within a view.

I get the message "Accessing Environment's value outside of being installed on a View. This will always read the default value and will not update."

and would like to work around that. I'm using Xcode 14.2

I do have a standard PersistenceController setup and so on

Here is where I run into the issue "let section = SectionsDB(context: managedObjectContext)"

@main
struct ArticlesExampleApp: App {
    let persistanceController = PersistanceController.shared    
    init() {
        let x = Articles.loadSections()
    }
    
    var body: some Scene {
        WindowGroup {
            MasterView()
                .environment(\.managedObjectContext, persistanceController.container.viewContext)
        }
    }


class Articles {
    class func loadSections() -> Int {
        @Environment(\.managedObjectContext) var managedObjectContext
        
        // Initialize some variables
        let myPath = Bundle.main.path(forResource: "Articles", ofType: "json")
        
        // Initialize some counters
        var sectionsCount = 0
        
        do {
            let myData = try Data(contentsOf: URL(fileURLWithPath: myPath!), options: .alwaysMapped)
            
            // Decode the json
            let decoded = try JSONDecoder().decode(ArticlesJSON.self, from: myData)
            
            // **here is where I run into the error on this statement**
            let section = SectionsDB(context: managedObjectContext)

            while sectionsCount < decoded.sections.count {
                print("\(decoded.sections[sectionsCount].section_name) : \(decoded.sections[sectionsCount].section_desc)")
                section.name = decoded.sections[sectionsCount].section_name
                section.desc = decoded.sections[sectionsCount].section_desc
                sectionsCount =1
            }
                PersistanceController.shared.save()
        } catch {
            print("Error: \(error)")
        }
        return sectionsCount
    }
}

CodePudding user response:

Since you are already using a singleton, you can just use that singleton in your loadSections function:

let section = SectionsDB(context: PersistanceController.shared.container.viewContext)

And, remove the @Environment(\.managedObjectContext) var managedObjectContext line

  • Related