简体   繁体   中英

Saving the context does not persist an updated NSManagedObject

In my app I have 2 detail view controllers:

  • product name update controller
  • product properties update controller

In product properties update view controller everything is fine there is nothing wrong.

In product name update view controller however saving the context does not give any error. I see that the product name change in root view controller but when I re-open my app the product name shows me the old name. So it is not persisted.

What is my problem according to my updateProduct method:

-(void)updateProduct:(id)sender
 {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Products" inManagedObjectContext:context]];

NSError *error = nil;

NSPredicate *predicateID =[NSPredicate predicateWithFormat:@"productID==%d",[secim intValue]];
[request setPredicate:predicateID];

NSArray *myobj=[context executeFetchRequest:request error:&error];
NSManagedObject *prod1=[myobj objectAtIndex:0];

[prod1 setValue:textProduct1.text forKey:@"productName"];



if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}


[self.navigationController popToRootViewControllerAnimated:YES];

NSLog(@"Data saved");
}

Check with a breakpoint if your updateProduct method is called. I suspect it is not.

In the light of the other discussion, make sure that

  • the managed object context is not nil
  • prod1 (the managed object) is not nil

You can do this with breakpoints in the debugger or with log statements.

In addition to @Mundi here you are doing the following

NSArray *myobj = [context executeFetchRequest:request error:&error];
NSManagedObject *prod1 = [myobj objectAtIndex:0];

but you are not checking against error and neither if myobj contains elements.

ALWAYS check for errors whereas there is the possibility to have them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM