Reputation: 863
I have an application that uses a UItableview
and a single UIViewController
. The UIViewController
is used for all of Add/Edit/View
I am able to add and view then switch to edit. The problem I am having is persisting the data in core data following an update.
Following an edit/update, the changes are visible in the Table View but upon application restart (or back from then forward to the table view) the changes are gone.
The tableview class sets the NSManagedObject
in prepareForSegue
as follows:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSManagedObject *selectedEntry = [fetchResultsArray objectAtIndex:indexPath.row];
DSAdd *wadd = [segue destinationViewController];
if ([segue.identifier isEqualToString: @"detailsSegue"])
{
wadd.callType = 2; //view details
wadd.selectedEntry = selectedEntry;
}
else
{
wadd.callType = 0; //add
}
}
In the view controller's header, I declare:
@property (strong) NSManagedObject *selectedEntry;
In the view controller's class I have the following Save method:
- (void) saveData
{
DBUtils *dbu = [[DBUtils alloc] init];
NSManagedObjectContext *context = [dbu managedObjectContext];
if (isEditMode) //<-- THIS PART DOES NOT WORK
{
NSLog(@"%@",[_selectedEntry valueForKey:@"name"]); //prints old value
[_selectedEntry setValue:_nameTF.text forKey:@"name"];
NSLog(@"%@",[_selectedEntry valueForKey:@"name"]); //prints new value
}
else // <-- THIS PART WORKS
{
NSManagedObject *newItem;
newItem = [NSEntityDescription insertNewObjectForEntityForName:@"Entry" inManagedObjectContext:context];
[newItem setValue:[NSNumber numberWithInt:1] forKey:@"catId"];
[newItem setValue:_nameTF.text forKey:@"name"];
} //else
NSError *error;
if (![context save:&error]) {
NSLog(@"Failed to save - error: %@", [error localizedDescription]);
}
[self.navigationController popViewControllerAnimated:YES];
}
Appreciate your help!
Upvotes: 0
Views: 115
Reputation: 2047
First you need to make sure that NSManagedObject that you’re using belongs to a context you’re trying to save.
Then you need to check how this context is configured. If it is configured with persistent store coordinator, then save will commit to the store. If it is configured with a parent context, then save will push changes to the parent instead of saving to the store. In this case, you need to save the parent and if it is configured with another parent, then save that one. The changes will go to the store when the last parent, the on that is configured with persistent store coordinator is saved.
Upvotes: 1
Reputation: 4005
I think there might be an issue with your context, try multi threading
Upvotes: 0