Search code examples
ioscore-datansmanagedobjectcontext

Core Data not Persisting


I'm having a problem with Core Data. I have a table view viewcontroller1 that is populated from an array that is populated with data in my Core Data model. When a cell is selected, it does a push segue to viewcontroller2, where you can view the saved data. From there, I have button called "edit" that, when selected, does a modal segue to viewcontroller3 where you can edit that data. Here's the code I have for saving the edited data.

//editModel

[self.editModel setValue:self.editNameTextField.text forKey:@"name"];
[self.editModel setValue:self.editTextView.text forKey:@"text"];
[self.editModel setValue:[NSDate date] forKey:@"date"];

NSError *error;
if (![[self.delegate managedObjectContext] save:&error])
{
    NSLog(@"Can't save the edit: %@", [error localizedDescription]);
}

if (self.delegate)
    [self.delegate dismissEdit:self];
else
    NSLog(@"There is no delegate");

However, whenever I try calling this, I get an NSLog: Can't save the edit: (null)

viewcontroller2 reflects the change; as does the table view in viewcontroller1. But, when I quit the iOS Simulator and run it again, I only get data previous to the editing process. Help?


Solution

  • Most likely the managed object context isn't being made available by the delegate. Rather than get it from the delegate, each managed object has a link to the managed object context that it is added to so you can do:

    [self.editModel.managedObjectContext save:&error]