mtStack mtStack - 4 months ago 33
Objective-C Question

Core data insert multiple objects

Is that the right way to save multiple objects with relationships? Or is there a way to improve the code and save the context just one time? Thanks!!

for (NSDictionary *entries in dataArray){
module = [NSEntityDescription insertNewObjectForEntityForName:@"Modules" inManagedObjectContext:context];
module.m_id=[entries objectForKey:@"id"];
module.m_name = [entries objectForKey:@"name"];
module.m_timestamp = [NSDate date];

//This line links the product by adding an entry to the NSSet of list for the module relation
[product addModulesObject:module];

//This line link the module with the product using product relation
[module setProduct:product];

NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}

Answer

You can move this code out of the loop.

NSError *error = nil;
if (![context save:&error]) {
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
     abort();
}