After you get an object and change its attributes, IF YOU DO NOT saveContext, you can rollback the data to its original value.
For example, say we get the first indexed Person object. You change the first name to Ricky. If you use [coreDataStack saveContext], that means the change is permanent in the database and you will be able to see the change when you restart up.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
-(void)changeFirstPerson { CoreDataStack * coreDataStack = [CoreDataStack defaultStack]; //Get all the projects in the data store NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:[self managedObjectContext]]; request.entity = entity; NSArray *listOfPeople = [[self managedObjectContext] executeFetchRequest:request error:nil]; //Rollback example Person *rollbackPerson = [listOfPeople objectAtIndex:0]; rollbackPerson.firstName = @"RICKY"; #warning - if you made a change without saveContext, context's hasChanges will be true. You can rollback. but if you saveContext, then you can't roll back and the hasChanges bool will be false. [coreDataStack saveContext]; //permanent save } |
But if we comment out [coreDataStack saveContext], that means the change is not permanent and is only in cache context. You will see the change in the current usage of the app, but if you restart the app, you will see the old value.
In other words, in the database, we have NOT updated the value.
When [coreDataStack saveContext] is commented out, the changes you make is ONLY reflected in the current usage of the app, and not in the database. Thus, you can rollback to the original value by first checking to see if there was a change on the context by using
[[coreDataStack managedObjectContext] hasChanges]. Then if there was a change, you rollback the value by doing [[coreDataStack managedObjectContext] rollback]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
-(BOOL)hasChanges { CoreDataStack * coreDataStack = [CoreDataStack defaultStack]; if([[coreDataStack managedObjectContext] hasChanges]) { NSLog(@"YES THERE WAS A CHANGE"); [[coreDataStack managedObjectContext] rollback]; return TRUE; } NSLog(@"NO THERE WAS NO CHANGES"); return FALSE; } |