Xcode 如何使用UISearchBar搜索NSMutableArray?
我找了很多地方,但都找不到答案,所以我决定提出我自己的问题 我使用JSON中的数据填充UITableView。我的数据结构如下:Xcode 如何使用UISearchBar搜索NSMutableArray?,xcode,nsmutablearray,uisearchbar,Xcode,Nsmutablearray,Uisearchbar,我找了很多地方,但都找不到答案,所以我决定提出我自己的问题 我使用JSON中的数据填充UITableView。我的数据结构如下: NSMutableArray* studentList = [(NSDictionary*)[responseString JSONValue] objectForKey:@"StudentList"]; JSON: 向UITableView添加数据: - (UITableViewCell *)tableView:(UITableView *)tableView c
NSMutableArray* studentList = [(NSDictionary*)[responseString JSONValue] objectForKey:@"StudentList"];
JSON:
向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编程还不熟悉。非常感谢。我认为这将有助于您了解如何将
NSMutableArray
与UISearchBar和UITableView结合使用。我从网上得到的例子是。也许这会帮助你解决你的问题
- (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;
}