Установка отношений при импорте базовых данных?

Тесты должны быть изолированы. Один тест не должен зависеть от другого. Еще больше тест не должен полагаться на внешние системы. Другими словами, протестируйте Ваш код, не код, от которого зависит Ваш код. Можно протестировать те взаимодействия как часть интеграционных тестов или функциональных испытаний.

6
задан Matthew 20 October 2009 в 03:13
поделиться

2 ответа

If the Department objects have already been saved to a persistent store, then you can bring them into another managed object context. Since your objects will all have to live in the same persistent store anyway (as cross-store relationships are not allowed), you should be able to simply fetch the ones you need into importMoc.

For example:

foreach (NSDictionary *record in employeeRecords) {
    NSManagedObject *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:importMoc];
    // Configure employee however you do that

    NSString *managerID = [record objectForKey:@"someKeyThatUniquelyIdentifiesTheManager"];
    NSFetchRequest *managerFetchRequest = [[NSFetchRequest alloc] init];
    [managerFetchRequest setEntity:[NSEntity entityForName:@"Manager" inManagedObjectContext:importMoc]];
    [managerFetchRequest setPredicate:[NSPredicate predicateWithFormat:@"managerProperty == %@", managerID]];
    NSArray *managers = [importMoc executeFetchRequest:managerFetchRequest error:nil]; // Don't be stupid like me and catch the error ;-)
    [managerFetchRequest release];

    if ([managers count] != 1) {
        // You probably have problems if this happens
    }

    [employee setValue:[managers objectAtIndex:0] forKey:@"manager"];
}

You could also just do a single fetch request to get all of the managers into importMoc and then filter that array to locate the right one each time. That would probably be a lot more efficient. In other words, don't do what I just told you to do above :-)

4
ответ дан 17 December 2019 в 07:06
поделиться

1 / предположим, что запись X сотрудника имеет имя Y и идентификатор отдела 15 (т.е. она ссылается на отдел с идентификатором 15 через отношение)

2 / загрузить отдел с идентификатором отдела 15 из управляемого объекта context

3 / создать сотрудника, который ссылается на объект, созданный в (2)

, т.е. (примечание: только пример кода, вероятно, не будет компилироваться):

NSEntityDescription * departmentED = [NSEntityDescription entityForName:@"Department" inManagedObjectContext:moc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id == %@)", deptId];

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:departmentED];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];

/* create employee */

NSEntityDescription * employeeED = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:moc];
NSManagedObject * employeeMO = [[[NSManagedObject alloc] initWithEntity:employeeED insertIntoManagedObjectContext:moc] autorelease];

/* set employee department to department instance loaded above */
[receiptObject setValue:[array objectAtIndex:0] forKey:@"department"];
0
ответ дан 17 December 2019 в 07:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: