1

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

我用来自 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 编程新手。非常感谢你。

4

1 回答 1

0

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

于 2012-07-04T12:19:53.573 回答