objective-ccore-datansmanagedobjectnsmanagedobjectmodel

How does the save method in Core Data works?


I'm following a guid in core data, and they implement an action method to preform saving to the database using a ManagedObject. I understand all the code in the method except the method which they say preform the saving, and to me it looks like the method checks if there is an error, and if yes so there is an NSLog to print that there was an error. this is the method:

- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];

    // creating a new managed object
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];

    [newDevice setValue:self.nameTextField.text forKey:@"name"];
    [newDevice setValue:self.versionTextField.text forKey:@"version"];
    [newDevice setValue:self.companyTextField.text forKey:@"company"];

    NSError *error = nil;

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

    [self dismissViewControllerAnimated:YES completion:nil];
}

Obviously something happens in [context save:&error] this call which I'd love if you can explain what?


Solution

  • Calling save: persists changes made to the object graph on the specific context and takes it one level above.

    Each context contains its own changeset, and when you call save:, the changes are either taken one level above (to its parent context), or, if there is no parent context, to the store coordinator to be persisted by the method specified when opening the coordinator (SQLite, XML, binary, etc.).

    Changes can be modifications, insertions or deletions.

    Before saving, changes to objects are verified and objects are notified about the save process.

    After saving, notifications are sent to the system to let know various components (such as fetch results controllers, your code, etc.) that the save operation has taken place.