Search code examples
objective-ciosxcodeuisearchbaruisearchdisplaycontroller

UISearchBar search two arrays


I Have a search bar that searches an array, and updates a UITableView with the results. The table view is a list of books, with titles and authors:

The titles and authors

Right now, the search bar only searches the titles but I would like to make it search the authors as well. Here is the search code I have (I got it from 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];

}

dataSource is the NSMutable Array that contains the titles. the array that contains the authors is called "author". "tableData" is the array that stores the cells that should appear on the screen (the cells that contain terms being searched for).

Thanks so much,

Luke


Solution

  • I would modify the dataSource array to contain both the titles and authors by creating an NSDictionary with key value pairs (a Book class would be better).

    //Do this for each book
    NSDictionary * book = NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
        title, @"TITLE", author, @"AUTHOR", nil];
    [dataSource addObject:book];
    

    After that you can change your search method to work with the NSDictionary instead.

    - (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];
    }
    

    Note using this method you would have the change your cellForRowAtIndexPath method to work with the NSDictionary and not the title strings.