Carpetfizz
Carpetfizz

Reputation: 9149

When is the managed object actually saving?

I have some code where I generate a new CoreData entity by doing the following:

SOModule* newModule = [NSEntityDescription insertNewObjectForEntityForName:@"SOModule" inManagedObjectContext:self.managedObjectContext];
        newModule.name = self.tf_name.text;
        newModule.ip = self.tf_ip.text;
        newModule.port = self.tf_port.text;
        newModule.user = self.tf_user.text;
        newModule.password = self.tf_pass.text;
        newModule.created = [NSDate date];

Then I call this fetch request to check for duplicate attributes:

 NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"SOModule"];
          fetchRequest.predicate = [NSPredicate predicateWithFormat:@"ip == %@",newModule.ip];
          NSArray* matchingModules = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
          NSLog(@"%@",[matchingModules description]);

This is before I save the "save" the entity, but I'm getting an array description of the information I JUST inputed, using the first block of code. To save it at the end, I do the following:

 [self.managedObjectContext save:nil];

I have a feeling that newModule is being saved in the first line of code, but it shouldn't be, since it is just an initializer. Any clarity would be great!

Upvotes: 0

Views: 42

Answers (1)

Martin R
Martin R

Reputation: 539775

insertNewObjectForEntityForName: creates the object and inserts it into the managed object context.

[self.managedObjectContext save:nil]

saves all changes in the context (such as the newly created object) to the persistent store (the SQLite file).

By default, a fetch request also includes unsaved changes, that's why it returns the new object before the context is saved.

You could exclude unsaved changes by setting

[request setIncludesPendingChanges:NO];

but the default value is YES.

Upvotes: 1

Related Questions