I am using core data in my iPhone app. I have created a simple class Friend, which derives from NSManagedObject and which uses the following property:
@property (nonatomic, retain) NSString *name;
I am able to add and delete instances of this class to my context and my changes are persistent also.
Now I want to update/modify a Friend-instance and make it persistent again.
But this seems not to work.
Here is piece of code which shows my problem:
// NSManagedObjectContext *context = < my managed context>
// NSFetchedResultsController *nsfrc= < my fetched result controller>
NSEntityDescription *entity = [nsfrc entity];
NSManagedObject *newManagedObject = [NSEntityDescription
insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
Friend *f = (Friend *) newManagedObject;
f.name = @"name1";
//1. --- here context.hasChanges == 1 --- ok
NSError *error = nil;
if (![context save:&error]) { ... }
//2. --- here context.hasChanges == 0 --- ok
f.name = @"name2";
//3. --- here context.hasChanges == 0 --- nok?
if (![context save:&error]) { ... }
At comment 1 everything is fine. I got a new NSManagedObject of the Friend-type and I can change the name property. The context shows me that there is something to save. After saving the context I see context.hasChanges == 0. Note also that the data is persistent after saving the context.
After comment 2 I change the name property. Now I would expect context.hasChanges == 1 and also after the context save I would expect the new name to be persistent. But unfortunately It is not. Starting the application again, loads the Friend instance with the name-property = @"name1".
I cannot find any hint or example inside the core data documentation. So what am I doing wrong? What do I have to do to update/modify an existing Friend-instance and to make it persistent?
The only solution I see is to delete the entry, change it, and add it again. But I don't think that this is the correct way for it.
Thanks!