TL;DR 我是核心数据新手。我对Core Data中Entity的理解是它类似于一个类。如果是这样,如何将实体的多个“实例”(NSManagedObjects?)保存到核心数据?似乎每次我保存托管对象时,都会覆盖之前写入的对象。
我喜欢我创建的实体 (MathFlashcard) 中包含的属性。我想将许多 MathFlashcard 保存到 Core Data,每个都有自己的属性。最好的方法是什么?
StackExchange 上似乎很多人都有同样的问题。基于这些我无法形成令人满意的答案。阅读苹果的文档同样被证明是徒劳的。通过阅读 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)
}
最佳答案
您需要为每个对象创建新实例。
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)")
}
关于swift - 如何在Core Data中保存一个实体的多个 "instances"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57881721/