如何使用UISearchBar搜索NSMutableArray?

时间:2012-07-03 11:56:51

标签: xcode nsmutablearray uisearchbar

我搜索了很多地方但找不到答案,所以我决定自己提出问题。

我使用JSON中的数据填充UITableView。我的数据结构是这样的:

NSMutableArray* studentList = [(NSDictionary*)[responseString JSONValue] objectForKey:@"StudentList"];

JSON:

{
"StudentList":[
    {
      "StudentID":"08DH11039",
      "StudentFirstName":"Nguyen Lam",
      "StudentLastName":"Binhh"
    },
    {
      "StudentID":"08DH11163",
      "StudentFirstName":"Nguyen Minh",
      "StudentLastName":"Duc"
    },
    {
      "StudentID":"08DH11038",
      "StudentFirstName":"Nguyen Bao",
      "StudentLastName":"Khuyen"
    },
    {
      "StudentID":"08DH11037",
      "StudentFirstName":"Nguyen Tran Duy",
      "StudentLastName":"Phuong"
    }
  ]
}

将数据添加到UITableView:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        NSDictionary *student = [studentList objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%d. %@ %@", indexPath.row+1, [student objectForKey:@"StudentFirstName"], [student objectForKey:@"StudentLastName"]];
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }

我还添加了一个UISearchBar,但它不起作用:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [searchData removeAllObjects];

    NSArray *student; 

    for(student in studentListCopy) //take the n group (eg. group1, group2, group3)
    {
        NSLog(@"%@", student);
        NSMutableArray *newGroup = [[NSMutableArray alloc] init];
        NSString *element;

        for(element in student)
            NSRange range = [element rangeOfString:searchString
                                           options:NSCaseInsensitiveSearch];

            if (range.length > 0) { //if the substring match
                [newGroup addObject:element]; //add the element to group
            }
        }

        if ([newGroup count] > 0) {
            [searchData addObject:newGroup];
        }
    }

    return YES;
}

请帮我搞定。我想搜索TableView中显示的FirstName或LastName。

我是iOS编程的新手。非常感谢你。

1 个答案:

答案 0 :(得分:0)

我认为这有助于您了解NSMutableArray如何与UISearchBar和UITableView一起使用。我从互联网上获得的例子是here。也许这会帮助你解决问题