搜索数组以查找与ObjectA.property匹配的ObjectB.property

时间:2014-02-12 15:55:57

标签: ios objective-c nsarray compare

我有2个数组填充了对象,两个对象都具有相同的属性teamID,每次点击屏幕时,TeamObject中的对象都被激活,我需要在ExtraTeamInfoObject中搜索匹配的teamID:

这是我到目前为止所做的,但不起作用:

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([[segue identifier] isEqualToString:@"teamDetailsSeg"]){

        TeamDetailsTableViewController *detailViewController = [segue destinationViewController];

        NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
        long row = [myIndexPath row];

        TeamObject *item = [tableData objectAtIndex:row];
    ExtraTeamInfoObject *item2 = _allInfo[row];

    ExtraTeamInfoObject *searchingObject;

    for (int i = 0; i < _allInfo.count && searchingObject; i++){

        for (ExtraTeamInfoObject *co in _allInfo[i]) {

            if (co.teamID == item.teamID) {

                searchingObject = item2;

                break;
                }
                }
                }


        detailViewController.teamDetailModel = item2;

        NSLog(@" Object %@", item.teamID);
        NSLog(@" Extra  %@", item2.teamID);

        }
}

不知怎的,这并没有让我的应用程序崩溃并且它可以工作,但是看看底部的两个NSLog打印,这就出现了:

2014-02-12 10:51:26.255对象531 2014-02-12 10:51:26.255 Extra 539

意思是它根本没有搜索到正确的对象。有谁知道解决这个问题?谢谢。

2 个答案:

答案 0 :(得分:0)

当您执行以下操作时,您似乎在枚举单个对象:

for (ExtraTeamInfoObject *co in _allInfo[i])

不应该:

for (ExtraTeamInfoObject *co in _allInfo)

答案 1 :(得分:0)

而不是for循环,我更倾向于使用NSPredicate,这要归功于KVC的优点:

ExtraTeamInfoObject *searchingObject;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"teamID == %@", item.teamID];
NSArray *result = [_allInfo filteredArrayUsingPredicate:predicate];

if (results.count) {
    searchingObject = [results firstObject];
}