核心数据插入多个对象

时间:2013-11-19 10:38:41

标签: objective-c object core-data insert

这是用关系保存多个对象的正确方法吗?或者有没有办法改进代码并保存上下文一次?谢谢!

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

2 个答案:

答案 0 :(得分:4)

您可以将此代码移出循环。

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

答案 1 :(得分:2)

创建每个对象后保存可能会带来性能问题,因此最好等到创建所有对象并保存上下文。

只需在通过数组后保存上下文:

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