在视图外向核心数据添加值时遇到麻烦



我正在尝试将数据加载到CoreData实体"文章"当我的应用程序启动时,我想从一个函数中调用init(){}调用,这意味着我没有从视图中执行此操作。

我得到消息"访问环境的值被安装在视图之外。这将始终读取默认值,而不会更新。">

,并希望解决这个问题。我使用的是Xcode 14.2

我有一个标准的PersistenceController设置等等

这就是我遇到问题的地方"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
}
}

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

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

并且,删除@Environment(.managedObjectContext) var managedObjectContext

最新更新