【发布时间】: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)
}
【问题讨论】:
-
我发现这与您的问题非常相关。所以也许这可能对stackoverflow.com/a/9841257/11815440 有所帮助,如果您使用许多相关实体,您也可以在这里查看:stackoverflow.com/a/5400158/11815440
-
要创建一个新实例,您可以使用初始化器,就像任何其他类一样,NSManagedObject 是您的实体的超类。请参阅链接中的“初始化托管对象”主题