I have from one side the NSManagedObject event that has a relationship one to many with the Entity Contacts.My app downloads contacts from the server, once all the contacts are downloaded I want to save them in CoreData keeping the relationship. Im wondering if I can save them in one go. All the contacts in an NSArray, contactsWeb, and push them into Core Data or I have to save each one of them like this:
NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
for(int i = 0; [contactsWeb count]; i++){
NSManagedObject *contact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];
[contact setValue:[contactsWeb objectAtIndex:i] forKey:@"text"];
[contact setValue:[NSDate date] forKey:@"date"];
[[event mutableSetValueForKey:@"toContacts"]addObject:contact];
NSError *error;
if(![context save:&error]){
NSLog(@"%@", [error localizedDescription]);
}
}
Saving a managed object context means that all changes in the context are saved to the persistent store (or to the parent context, in the case of nested contexts). So you can (and should) save the context “in one go” after all contacts have been inserted and the relationships been set.
Remark: If you create managed object subclasses
ContactsandEventfor your entities, your code can be simplified toThe managed object subclasses can be created in Xcode: Select the entities in the Core Data model editor and choose “Editor -> Create NSManagedObject subclass …” from the menu.