swift 向视图外部的核心数据添加值时遇到问题

jhkqcmku  于 2023-01-12  发布在  Swift
关注(0)|答案(1)|浏览(114)

我正在尝试将数据从函数加载到CoreData实体“Articles”中,我希望在应用启动时在init(){}调用中调用该函数,这意味着我没有在视图中执行此操作。
我收到消息“访问未安装在视图上的环境值。这将始终读取默认值,不会更新。”
我想解决这个问题。我使用的是Xcode 14.2
我有一个标准的PersistenceController设置等等
在这里我遇到了问题“let section = SectionsDB(上下文:托管对象上下文)”

@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
    }
}
uxh89sit

uxh89sit1#

既然你已经在使用单例了,你可以在你的loadSections函数中使用这个单例:

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

然后,删除@Environment(\.managedObjectContext) var managedObjectContext

相关问题