【问题标题】:How do I save multiple "instances" of an entity in Core Data?如何在 Core Data 中保存实体的多个“实例”?
【发布时间】:2019-09-11 03:28:37
【问题描述】:

TL;DR 我是 Core Data 的新手。我对 Core Data 中实体的理解是它类似于一个类。如果是这样,我如何将实体的多个“实例”(NSManagedObjects?)保存到核心数据?似乎每次我保存我的托管对象时,我都会覆盖之前写的那个。

我喜欢我创建的实体 (MathFlashcard) 中包含的属性。我想将许多 MathFlashcards 保存到 Core Data,每个都有自己的属性。最好的方法是什么?

StackExchange 上的很多人似乎都有同样的问题。我无法根据这些形成令人满意的答案。阅读 Apple 的文档同样被证明是徒劳的。我也没有通过阅读 Ray Wenderlich 和 Big Ranch 的教程来回答这个问题。

编辑:我尝试将每个实体的声明移动到 for 循环中,但我仍然遇到错误和错误。我在下面粘贴了我的代码!也许有人可以发现问题所在。

@IBAction func makeCardsAndSave(_ sender: UIButton) {

        // Access the managed context
        let context = persistentContainer.viewContext

        // Create an entity
        let entity = NSEntityDescription.entity(forEntityName: "MathFact", in: context)!

        //Create FlashCards
        let flashCards: FlashCards = FlashCards(properties: selectedFacts)

        for fact in flashCards.facts {
            if !fact.isEmpty {
                let newFact = NSEntityDescription.insertNewObject(forEntityName: "MathFact", into: context) as NSManagedObject
                newFact.setValue(fact[0], forKeyPath: "firstInteger")
                newFact.setValue(fact[1], forKeyPath: "secondInteger")
                newFact.setValue(fact[2], forKeyPath: "ans")
                newFact.setValue(fact[3], forKeyPath: "box")
            }

            // Try to save
            do {
                try context.save()
            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
            }

        }

        // Testing the save
        fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "MathFact")

        var testFetch: [NSManagedObject] = []
        do {
            testFetch = try context.fetch(fetchRequest)
        } catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }

        print(testFetch)
    }

【问题讨论】:

标签: swift core-data


【解决方案1】:

您需要为每个对象创建新实例。

import CoreData

let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let entity_ mathFlashcard =  NSEntityDescription.entity(forEntityName: "MathFlashcard", in:managedContext)

for _ in 1..<10 {
    let mathFlashcard = MathFlashcard(entity: entity_ mathFlashcard!, insertInto: managedContext)
    mathFlashcard.title = "Title"
    // your other attributes
}

do {
     try managedContext.save()
} catch let error as NSError  {
     print("Could not save \(error), \(error.userInfo)")
}

【讨论】:

  • 这很有帮助,谢谢。我想我明白你在说什么。澄清一下,您在示例代码中实现的 MathFlashcard 是 NSManagedObject 的子类,对吗?
  • 没错,我以为你是这样的吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
相关资源
最近更新 更多