Search code examples
iosobjective-cios7

How to filter search within a set of letters in search bar so that each letter typed will reduce the results in objective -c


i have implemented a search bar that searching trough an array of countries(presented in a picker view), the problem is that the user need to type the full country name that it will find it and i want him to be able to type even one letter and it will show the first country that starts with that letter and if types another than it sorts even further etc etc. Anyone have any ideas??

for(int x = 0; x < countryTable.count; x++){

    NSString *countryName = [[countryTable objectAtIndex:x]objectForKey:@"name"];

    if([searchedStr isEqualToString:countryName.lowercaseString]){

        [self.picker selectRow:i inComponent:0 animated:YES];

        flag.image = [UIImage imageNamed:[[countryTable objectAtIndex:i]objectForKey:@"flag"]];
    }
}

Solution

  • There's a method on NSArray called filteredArrayUsingPredicate: and a method on NSString called hasPrefix:. Together they do what you need...

    NSString *userInput = //... user input as lowercase string.  don't call this countryName, its confusing
    NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id element, NSDictionary *bind) {
        NSString countryName = [[element objectForKey:@"name"] lowercaseString];
        return [countryName hasPrefix:userInput];
    }];
    NSArray *filteredCountries = [countryTable filteredArrayUsingPredicate:p];