我如何从ModelObject访问NSSet有什么问题?

时间:2010-03-05 22:03:58

标签: iphone cocoa-touch core-data

我一直在试图掌握Core Data,而且我对取得的结果有些困难。问题是我有'Branch'对象与'Telephone'对象有很多关系。当我返回“分支”并尝试从返回的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

1 个答案:

答案 0 :(得分:1)

问题在于此代码:

// 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"]);
}

对于for循环的每次迭代,newTelephone对象都是SAME 因此,这一行只是向集合中添加了一个对象(它被添加了多次,但是NSSet不允许重复,而且这实际上并不是你想要的):

[newBranch addTelephoneObject:newTelephone];