2013-11-19 2 views
5

Это правильный способ сохранить несколько объектов с отношениями? Или есть способ улучшить код и сохранить контекст всего один раз? Благодаря!!Основные данные вставляют несколько объектов

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

ответ

3

Вы можете переместить этот код из цикла.

NSError *error = nil; 
if (![context save:&error]) { 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 
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(); 
} 
Смежные вопросы