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?

4

1 回答 1

1

调用save:将在特定上下文中对对象图所做的更改保持不变,并将其提升到上一级。

每个上下文都包含自己的变更集,当您调用 时save:,这些更改要么在上一级(对其父上下文)进行,或者,如果没有父上下文,则通过打开时指定的方法保存到存储协调器协调器(SQLite、XML、二进制等)。

更改可以是修改、插入或删除。

在保存之前,会验证对对象的更改并通知对象有关保存过程的信息。

保存后,系统会向系统发送通知,以告知已发生保存操作的各种组件(例如获取结果控制器、您的代码等)。

于 2014-04-16T00:49:50.787 回答