looking for some solutions? You are welcome.

SOLVED: Core data not retaining older values

Maddie Drake:

When I save to Core Data and then try to read from it, only the most recently saved value is retained.
The rest are nil when I try to print them out.

In my .xcdatamodeld, my entity is named CD_Cookbook and it has an attribute of name.
I'm not sure what I'm doing wrong.

func newCookbook(cookbook: String) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext

    let entity = NSEntityDescription.entity(forEntityName: "CD_Cookbook", in: managedContext)!
    let item = NSManagedObject(entity: entity, insertInto: managedContext)
    item.setValue(cookbook, forKey: "name")
    do {
        try managedContext.save()
    catch {
        print("did not save cookbook name to core data", error)

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CD_Cookbook")
    do {
        let cd = try managedContext.fetch(fetchRequest)
    catch {
        print("Failed to fetch cookbook names from Core Data", error)

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots

No comments: