Я пытался справиться с Core Data, и у меня возникли некоторые трудности с полученными результатами. Проблема в том, что у меня есть объекты «Филиал», которые имеют отношение «многие» к объектам «Телефон». Когда я возвращаю «Ветвь» и пытаюсь получить доступ ко всем связанным объектам «Телефон» из возвращенного NSSet
, мне кажется, что я возвращаю только один объект. Посмотрите код ниже, который я использую, чтобы увидеть, что происходит.
/***************************************************************************************
start testing the fetched objects
***************************************************************************************/
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (int i=0; i<[results count]; i++) {
NSString *sortcode = [[results objectAtIndex:i] valueForKey:@"sortcode"];
NSString *lat = [[results objectAtIndex:i] valueForKey:@"latitude"];
NSString *lon = [[results objectAtIndex:i] valueForKey:@"longitude"];
NSSet *phoneSet = [[results objectAtIndex:i] valueForKey:@"telephone"];
int phoneCount = [phoneSet count];
NSArray *phoneArray = [self arrayFromSet:[[results objectAtIndex:i] valueForKey:@"telephone"]];
for (int j=0; j<[phoneArray count]; j++) {
NSString *phoneNumber = [[phoneArray objectAtIndex:j] valueForKey:@"number"];
NSLog(@"%@,%i,%i",phoneNumber,[phoneArray count],phoneCount);
}
NSLog(@"%@,%@,%@",sortcode,lat,lon);
}
/***************************************************************************************
finish testing the fetched objects
***************************************************************************************/
Это приводит к следующему выводу:
2010-03-05 22:05:18.566 AIB[3175:207] 059 9151727,1,1
2010-03-05 22:05:18.566 AIB[3175:207] 933325,52.802288,-6.737655
Вот где я добавляю объекты в контекст:
// Add all telephones to this branch
for (int i=0; i<[telephoneArray count]; i++) {
[newTelephone setBranch:newBranch];
[newTelephone setNumber:[[telephoneArray objectAtIndex:i] valueForKey:@"number"]];
[newBranch addTelephoneObject:newTelephone];
NSLog(@"i=%i and phone number=%@", i, [newTelephone valueForKey:@"number"]);
}
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
NSLog(@"Save failed with error %@",error);
} else {
NSLog(@"Save was successful");
}
... и вот результат вышеупомянутого
2010-03-05 22:15:03.217 AIB[3175:6837] i=0 and phone number=059 9151204
2010-03-05 22:15:03.218 AIB[3175:6837] i=1 and phone number=059 9151179
2010-03-05 22:15:03.218 AIB[3175:6837] i=2 and phone number=059 9151727
2010-03-05 22:15:03.231 AIB[3175:6837] Save was successful