【发布时间】:2021-11-05 16:36:21
【问题描述】:
我正在开发一个 iOS 应用程序。我已经在 AppDelegate.swift 中编写了一些代码,但后来意识到我需要使用 CoreData 数据结构。我使用本教程将其集成到我的代码中:(https://welcm.uk/blog/adding-core-data-to-an-existing-project-in-xcode-10-swift-4)。
我进入 my-model-name.xcdatamodeld 文件并创建了我的实体(它有两个字符串属性)。
在我的 AppDelegate 文件中,在 didReceiveRemoteNotification 中,我已将一个新实体对象添加到 CoreData 数据结构中,如下所示:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//omitted code to obtain information to store in atributes
let managedContext = persistentContainer.viewContext
let newUser = Info(context: managedContext)
newUser.title = title
newUser.body = body
}
... 'title' 和 'body' 是字符串变量。
现在,我如何检查该对象是否正确存储在 CoreData 中?
编辑
我已将try managedContext.save() 添加到我的代码中。我还有一个问题;我正在尝试在我的 ContentView.swift 中打印出存储在 CoreData 中的所有实体。这是我的代码:
struct ContentView: View {
@FetchRequest(
entity: Info.entity(),
sortDescriptors: []
) var languages: FetchedResults<Info>
var body: some View {
List(languages, id: \.self) { language in
Text(language.title ?? "Unknown")
}
}
}
在List(languages, id: \.self) { language in 行中,我收到一条错误消息,内容为“线程 1:EXC_BREAKPOINT (code=1, subcode=0x19d012818)”。我无法弄清楚为什么会这样。有什么建议吗?
【问题讨论】:
-
直到您在托管对象上下文中调用
save时才会存储它。您可以使用NSFetchRequest获取对象 -
添加、更新、删除后保存上下文。添加这一行 do { try managedContext.save() } catch { }