如何在核心数据中保存一个实体的多个“实例”?

时间:2019-09-11 03:28:37

标签: swift core-data

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

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

在StackExchange上似乎有很多人有同样的问题。基于这些我无法给出令人满意的答案。阅读苹果的文档同样被证明是徒劳的。通过阅读Ray Wenderlich和Big Ranch教程,我也没有对这个问题形成答案。

edit:我尝试将对每个实体的声明移到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)
    }

1 个答案:

答案 0 :(得分:0)

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

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)")
}
相关问题