Core data insert multiple objects

亡梦爱人 提交于 2020-01-14 09:48:59

问题


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();
    }
}

回答1:


You can move this code out of the loop.

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



回答2:


Saving after every object is created could bring performance problems, so it's better to wait until all objects are created and save the context.

Just save the context after going trough the array:

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();
}


来源:https://stackoverflow.com/questions/20069211/core-data-insert-multiple-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!