我正在尝试将数据从函数加载到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
}
}
1条答案
按热度按时间uxh89sit1#
既然你已经在使用单例了,你可以在你的
loadSections
函数中使用这个单例:然后,删除
@Environment(\.managedObjectContext) var managedObjectContext
行