Swift:使用 self.moc.save() 保存核心数据时出现 Nil 错误 [英] Swift: Nil Error when using self.moc.save() to save in core data
问题描述
由于我将项目更改为使用objectWillChange.send()",因此我得到了零错误.因为我需要手动更新视图,因为它不会为自定义轮播视图更新自身(因为核心数据?).
I get nil error since I changed my project to use 'objectWillChange.send()'. Because I needed to update the view manually since it doesn't update itself for custom carousel view(because of core data?).
如果我写1"然后点击下一个按钮(NavigationLink)
If I write "1" and tap the next button(NavigationLink)
控制台日志
页面名称:1
捕获错误:nilError
Console log
page.name: 1
catch error: nilError
这是代码.
AddPage 类
class AddPage: ObservableObject {
@Environment(\.presentationMode) var presentation
@Environment(\.managedObjectContext) var moc
func addPage(item: String) {
if item != "" {
let page = Page(context: self.moc)
page.name = item
do {
print("page.name: \(page.name ?? "Unknown")")
try self.moc.save()
} catch {
print("catch: \(error)")
}
objectWillChange.send()
presentation.wrappedValue.dismiss()
}
}
}
AddPageView
@ObservedObject var add = AddPage()
NavigationLink(destination: ContentView()){
Text("Next")
.background(
Rectangle()
.frame(width: 330, height: 60, alignment: .center)
)
.onTapGesture {
add.addPage(item: pageName)
}
}
SceneDelegate 类
added only
var addpage = AddPage()
let contentView = ContentView()
.environment(\.managedObjectContext, context)
.environmentObject(addpage)
有人可以帮我吗..?
推荐答案
更改
@Environment(\.managedObjectContext) var moc
例如(如果您使用的是 Xcode 生成的示例代码)如果不是手动获取您的 moc
但是您设置了它
To something like (If you are using the sample code that Xcode generates) if not manually get your moc
however you set it up
var moc = PersistentController.shared.container.viewContext
@Environment
包装器在 class
中不一致,它们只能在 SwiftUI View
中使用.
@Environment
wrappers are inconsistent in a class
they should only be used in a SwiftUI View
.
如果您没有 PersistentController
,请从具有 SwiftUI 生命周期和 CoreData 的全新项目中获取代码.小心并保留原始堆栈中的名称,它通常是应用程序名称
If you don't have a PersistentController
get the code from a brand new project with SwiftUI lifecycle and CoreData. Be CAREFUL and keep the name from the original stack it is usually the app name
从SceneDelegate 和
创建一个变量
let context = PersistentController.shared.container.viewContext
所以你可以在你的 View
这篇关于Swift:使用 self.moc.save() 保存核心数据时出现 Nil 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!