2012-07-16 44 views
1

我有2個實體,單位和BUnits,單位實體有一個數據將被多次替換,並且在清除數據之前,BUnits將成爲單位實體的備份。ios核心數據 - 將實體記錄複製到另一實體

所以,我創建了一個NSManagedObjectContext實例,那麼我就用

NSManagedObjectContext *context = [mainDelegate managedObjectContext]; 

NSEntityDescription *unitsEntity = [NSEntityDescription entityForName:@"Units" inManagedObjectContext:context]; 

NSEntityDescription *bUnitsEntity = [NSEntityDescription entityForName:@"BUnits" inManagedObjectContext:context]; 

retrive爲每個實體實例,但我已經沒有管理的單位實體記錄複製到BUnits實體,而不是爲每個記錄創建一個循環,但我相信有一個更好的解決方案。

您對此有何看法,有沒有更好的解決方案?

UPDATE:

我在任何情況下使用該解決方案可以使用它在我的回答,我認爲這是一個更好的方式來做到這一點,我會繼續檢查它,我會更新如果我發現任何問題的問題。

回答

1

這裏是我用過的,使用循環爲每個記錄:

- (void) copyEntities:(NSString *)sourceEntity And:(NSString *)destinationEntity { 
NSManagedObjectContext *context = [mainDelegate managedObjectContext]; 

NSEntityDescription *Units = [NSEntityDescription entityForName:sourceEntity inManagedObjectContext:context]; 
NSEntityDescription *BUnits = [NSEntityDescription entityForName:destinationEntity inManagedObjectContext:context]; 

NSFetchRequest *dataRequest = [[NSFetchRequest alloc] init]; 

[dataRequest setEntity:Units]; 

NSError *error = nil; 

NSArray *dataArray = [context executeFetchRequest:dataRequest error:&error]; 

for (UnitsClass *unit in dataArray) { 

    UnitsClass *savedUnits; 

    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    [request setEntity:BUnits]; 
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(code = %@)", unit.code]; 
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"(code2 = %@)", unit.code2]; 

    NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:pred, pred1, nil]]; 

    [request setPredicate:compoundPredicate]; 

    NSError *error = nil; 

    NSArray *objects = [context executeFetchRequest:request error:&error]; 

    //this if to indicate if we inserting to the BUnits or updating it. 
    if ([objects count] > 0) { 
     //Found the record, update The info 
     savedUnits = [objects objectAtIndex:0]; 
    } else { 
     savedUnits = [NSEntityDescription insertNewObjectForEntityForName:destinationEntity inManagedObjectContext:context]; 
    } 

    savedUnits.code = unit.code; 
    /*Add your updated info*/ 

    NSError *errors; 
    if (![context save:&errors]) { 
     NSLog(@"Whoops, couldn't save: %@", [errors localizedDescription]); 
    } 
} 

NSLog(@"BUnits count = %d",[context countForFetchRequest:[NSFetchRequest fetchRequestWithEntityName:destinationEntity] error:&error]); 
} 
0

根據給定的信息,沒有比循環每個單元對象和創建備份對象更好的方法。

+0

謝謝你的回覆,我將更新我一直在使用的情況下,任何人的循環將使用由該解決方案的問題它。 – Scar 2012-07-16 13:21:58

相關問題