Cannot fetch the entries of core data


Cannot fetch the entries of core data
I have below code that it will populate the core database with entries from struct array.
When I debug it seems that is sending correctly the data to the func iterateCoreData, but when I try to fetch the result I don't get anything.
What it could possible be wrong that either not add the data to database or couldn't fetch them.
I have tried the main syntax of saving and fetching with a plain array it works correctly.
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!")
}
for id in journalNoteArray.id {
let data = NSManagedObject(entity: entity, insertInto: managedObjectContext)
data.setValue(id, forKey: "id")
}
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 {
print("the id is: (id)")
}
}
}
} 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")
}
}
and the iterateCoreData func is the below:
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)
}
}
The issue is that I need to save on the database row by row and not as attribute per attribute for each entity. How I could resolve this?
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.