1

我有 2 个实体,Units 和 BUnits,Units 实体有一个数据会被多次替换,BUnits 将是 Units 实体在清除数据之前的备份。

所以,我创建了一个NSManagedObjectContext实例,然后我通过使用为每个实体检索了一个实例

NSManagedObjectContext *context = [mainDelegate managedObjectContext];

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

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

但我没有设法将 Units 实体记录复制到 BUnits 实体,除了为每个记录创建一个循环,但我相信有更好的解决方案。

您对此有何看法,有更好的解决方案吗?

更新:

如果有人可以使用它,我使用的解决方案在我的回答中,我认为有更好的方法可以做到这一点,我会继续检查它,如果我发现任何问题,我会更新问题。

4

2 回答 2

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]);
}
于 2012-07-26T07:24:27.853 回答
0

根据给定的信息,没有比循环每个单元对象并创建备份对象更好的方法了。

于 2012-07-16T12:45:43.447 回答