【问题标题】:CoreData: How to Insert an Object into CoreData data structure?CoreData:如何将对象插入 CoreData 数据结构?
【发布时间】: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 { }

标签: ios swift core-data


【解决方案1】:

您需要调用managedContext.save() 将其保存到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
    // a try catch block for error handling.
    do {
        try managedContext.save()
    } catch {
        print("Could not save.", error.localizedDescription)
    }
}

【讨论】:

  • 明白了。现在,在 ContextView.swift 中,我试图在“列表视图”中打印出存储在 CoreData 中的所有实体。我已经更新了我的原始帖子以包含这个问题。请看一看。
  • @DarrelGulseth 那是一个不同的问题。请接受此答案并添加一个新问题。请在此处分享链接,我很乐意为您解答。
【解决方案2】:

在任何更新之后,保存管理对象上下文会将所有当前更改提交到上下文的父存储。 在您的情况下,只需调用 AppDelegate.swift 上已有的“saveContext”方法即可。

    /* Do your Operation like Create, Update or delete*/

    self.saveContext()

【讨论】:

  • 我已经添加了这个。现在,在 ContextView.swift 中,我试图在“列表视图”中打印出存储在 CoreData 中的所有实体。我已经更新了我的原始帖子以包含这个问题。请看一下。 ——
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多