2012-07-03 49 views
1

我搜索了很多地方,但找不到答案,所以我決定設置自己的問題。如何使用UISearchBar搜索NSMutableArray?

我使用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中的名字或姓氏。

我是新來的iOS編程。非常感謝你。

回答

0

我認爲這對你理解NSMutableArray如何與UISearchBar和UITableView一起使用會有幫助。我從互聯網上得到的例子是here。也許這會幫助你解決你的問題