0

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?

neowinston
  • 7,584
  • 10
  • 52
  • 83
JohnBigs
  • 2,691
  • 3
  • 31
  • 61
  • 1
    That's the beauty of implementation details: you shouldn't care what happens so long as the overarching goal is accomplished. – CodaFi Apr 16 '14 at 00:23
  • Don't you also wonder what happens when you call `setValue:forKey:`? Or `NSLog`? Or `dismissViewControllerAnimated:completion:`? – Léo Natan Apr 16 '14 at 00:31
  • @LeoNatan The call to setValue:forKey: is something that make sense, just from the name you understand what is happening. but [context save:&error] is not clear to me, i'm not looking for step by step explanation, just an idea – JohnBigs Apr 16 '14 at 00:37
  • 1
    It checks if there are any changes in entities, calls all validators, pasesses changes to persistent store, which translates changes to sql queries, which are passed to sqlite, which stores them on disk :) – thom_ek Apr 16 '14 at 00:47

1 Answers1

1

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.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195