foobar5512
foobar5512

Reputation: 2490

Core Data Relationship Not Persisting

I am attempting to add an entity to a set but it is not persisting after the application is closed. My relationship looks like this:

enter image description here

I create a new Task like this:

 guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    // 1
    let managedContext =
        appDelegate.persistentContainer.viewContext

    // 2
    let entity =
        NSEntityDescription.entity(forEntityName: "Task",
                                   in: managedContext)!


    let task = NSManagedObject(entity: entity,
                                insertInto: managedContext)

    // 3
    task.setValue(cell.taskTextField.text, forKeyPath: "name")

    // 4
    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }

I add the task to a group entity like this:

 groups[0].mutableSetValue(forKey: "tasks").add(task)

Where groups is a NSManagedObject array whose value is loaded in viewDidLoad: like so:

   //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Group")


    //3
    do {
        groups = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }

The groups populate properly, I have all the groups I created. But no relationships are present. This prints nothing:

  let set = groups[0].mutableSetValue(forKey: "tasks")
    for tasks in set{
        print(tasks)
    }

This code prints the tasks provided I don't open and close the app. For some reason the data is not persisting when the app is closed. Any Ideas? Thanks

Upvotes: 0

Views: 375

Answers (1)

Minimi
Minimi

Reputation: 961

Make sure you're saving your context all the way back to up the persistent store (not just the parent context).

Upvotes: 1

Related Questions