使用UISearchBar搜索

时间:2012-01-31 16:43:55

标签: iphone objective-c cocoa-touch uisearchbar

我在导航栏中添加了一个搜索栏。当用户键入单词并单击搜索按钮(键盘)时,我需要在与搜索相关的表格中显示结果。

当我点击“搜索”时,我得到空白记录(它实际上进入if方法中的searchBarSearchButtonClicked:条件并添加了动物对象。我认为

存在问题
[mutableArray addObject:animal];
...
self.animalArray = mutableArray;    
[self.tableView reloadData];

我的完整代码如下。

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.mutableArray removeAllObjects];
    for (Animal *animal in self.animalArray) {
        if ([[animal nameOfAnimal] isEqualToString:[searchBar text]] ) {                
            [mutableArray addObject:animal];
        }
    }
    self.animalArray = mutableArray;    
    [self.tableView reloadData];
    [searchBar resignFirstResponder];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {        
        Animal *animal = [self.animalArray objectAtIndex:indexPath.row];        
        cell = [[Cell alloc] initWithStyle:UITableViewCellStyleDefault 
                           reuseIdentifier:CellIdentifier];
        cell.nameofani.text=animal.nameOfAnimal;   
        cell.oriofani.text=animal.originOfAnimal;  
    }
    return cell;
}

2 个答案:

答案 0 :(得分:2)

确保正确实施tableView:numberOfRowsInSection:,并在搜索结果表视图中返回[self.animalArray count]

答案 1 :(得分:1)

尝试:

self.animalArray = [mutableArray copy];