UISearchBar搜索两个数组

Luk*_*ann 2 xcode objective-c uisearchbar uisearchdisplaycontroller ios

我有一个搜索数组的搜索栏,并用结果更新UITableView.表格视图是书籍列表,包括标题和作者:

标题和作者

现在,搜索栏只搜索标题,但我想让它搜索作者.这是我的搜索代码(我从http://blog.webscale.co.in/?p=228获得).

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [tableData removeAllObjects];// remove all data that belongs to previous search
    if([searchText isEqualToString:@""]||searchText==nil){
        [tableView reloadData];
        return;
    }

    for(NSString *name in dataSource){
         NSInteger counter = 0;

        //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        NSRange r = [[name lowercaseString] rangeOfString:[searchText lowercaseString]];
        if(r.location != NSNotFound)
            [tableData addObject:name];


            counter++;
    }
        //[pool release];


    [tableView reloadData];
Run Code Online (Sandbox Code Playgroud)

}

dataSource是包含标题的NSMutable Array.包含作者的数组称为"作者"."tableData"是存储应该出现在屏幕上的单元格的数组(包含要搜索的术语的单元格).

非常感谢,

卢克

Joe*_*ets 8

我会修改dataSource数组以包含标题和作者,方法是创建一个带有键值对的NSDictionary(Book类会更好).

//Do this for each book
NSDictionary * book = NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    title, @"TITLE", author, @"AUTHOR", nil];
[dataSource addObject:book];
Run Code Online (Sandbox Code Playgroud)

之后,您可以更改搜索方法以使用NSDictionary.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

    [tableData removeAllObjects];

    if(searchText != nil && ![searchText isEqualToString:@""]){

        for(NSDictionary * book in dataSource){
            NSString * title = [book objectForKey:@"TITLE"];
            NSString * author = [book objectForKey:@"AUTHOR"];

            NSRange titleRange = [[title lowercaseString] rangeOfString:[searchText lowercaseString]];
            NSRange authorRange = [[author lowercaseString] rangeOfString:[searchText lowercaseString]];

            if(titleRange.location != NSNotFound || authorRange.location != NSNotFound)
                [tableData addObject:book];
            }

    }

    [tableView reloadData];
}
Run Code Online (Sandbox Code Playgroud)

注意使用此方法,您可以更改cellForRowAtIndexPath方法以使用NSDictionary而不是标题字符串.