我有以下代码,它将用来自struct数组的条目填充核心数据库。 当我调试时,似乎可以正确地将数据发送到func iterateCoreData函数,但是当我尝试获取结果时,我什么也没得到。
未将数据添加到数据库或无法获取数据可能是错误的。
我尝试了使用普通数组进行保存和获取的主要语法,
let managedObjectContext = self.persistentContainer.viewContext
// this is the working method to save data to core data and then fetch it.
/*
guard let entity = NSEntityDescription.entity(forEntityName: "Journal", in: managedObjectContext) else {
fatalError("There is no such entity!")
}
let count = journalNoteArray.id.count
for i in 0..<count {
let data = NSManagedObject(entity: entity, insertInto: managedObjectContext)
data.setValue(journalNoteArray.id[i], forKey: "id")
data.setValue(journalNoteArray.date[i], forKey: "date")
data.setValue(journalNoteArray.journal[i], forKey: "journal")
data.setValue(journalNoteArray.userID[i], forKey: "userID")
data.setValue(journalNoteArray.editDate[i], forKey: "editDate")
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Journal")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "id", ascending: true)]
do {
if let results = try managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] {
for result in results {
if let id = result.value(forKey: "id") as? Int, let date = result.value(forKey: "date"), let note = result.value(forKey: "journal") {
print("the id is: \(id), the date entered is: \(date) and the note is: \(note)")
}
}
}
} catch {
print("there was an error fetching the results")
}
*/
let journalMirror = Mirror(reflecting: journalNoteArray)
for journal in journalMirror.children {
self.iterateCoreData(givenArray: (journal.value as? Array)!, recEntity: "Journal", recKey: journal.label!)
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Journal")
do {
if let results = try managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] {
for result in results {
if let id = result.value(forKey: "id") as? Int, let date = result.value(forKey: "date"), let journal = result.value(forKey: "journal") {
print("the id is: \(id) created on date: \(date) with note: \(journal)")
}
}
}
} catch {
print("there was an error fetching the results")
}
}
和iterateCoreData函数如下:
func iterateCoreData(givenArray: Array<Any>, recEntity: String, recKey: String) {
let managedObjectContext = self.persistentContainer.viewContext
guard let entity = NSEntityDescription.entity(forEntityName: recEntity, in: managedObjectContext) else {
fatalError("There is no such entity!")
}
for entry in givenArray {
let data = NSManagedObject(entity: entity, insertInto: managedObjectContext)
print(recKey, entry)
data.setValue(entry, forKey: recKey)
}
}
问题是我需要逐行保存在数据库中,而不是每个实体的每个属性保存。我该如何解决?