Ios 如何在搜索栏中的一组字母中过滤搜索,以便键入的每个字母都会减少objective-c中的结果

Ios 如何在搜索栏中的一组字母中过滤搜索,以便键入的每个字母都会减少objective-c中的结果,ios,objective-c,ios7,Ios,Objective C,Ios7,我已经实现了一个搜索栏,可以通过一系列国家进行搜索(以picker视图显示),问题是,用户需要输入完整的国家名称,它将找到它,我希望他能够键入甚至一个字母,它将显示第一个国家,以该字母开头,如果键入其他比它排序更进一步等等。 有人有什么想法吗 for(int x = 0; x < countryTable.count; x++){ NSString *countryName = [[countryTable objectAtIndex:x]objectForKey:@"name"

我已经实现了一个搜索栏,可以通过一系列国家进行搜索(以picker视图显示),问题是,用户需要输入完整的国家名称,它将找到它,我希望他能够键入甚至一个字母,它将显示第一个国家,以该字母开头,如果键入其他比它排序更进一步等等。 有人有什么想法吗

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"]];
    }
}
for(int x=0;x
如果您使用的是iOS 8或OS X Yosemite,您可以执行以下操作:

NSString *country = countryName.lowercaseString; //"england"
NSString *needle = @"engl"; 
if (![country containsString:needle]) {
    NSLog(@"Country string does not contain part (or whole) of searched country");
} else {
    NSLog(@"Found the country!");
}
否则,如果在iOS 8以下的版本上:

NSString *country = countryName.lowercaseString; //"england"
NSString *needle = @"engl"; 
if ([country rangeOfString:needle].location == NSNotFound) {
    NSLog(@"Country string does not contain part (or whole) of searched country");
} else {
    NSLog(@"Found the country!");
}

最后,只需遍历所有可能的国家,并将其应用于所有国家。可能存在更健壮的解决方案(如danh的解决方案,有一些较小的修改),但这是最容易开始的。

NSArray上有一个名为
FilteredarrayingPredicate:
的方法,NSString上有一个名为
hasPrefix:
的方法。他们一起做你需要的

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

显示已实现的
UISearchBarDelegate
方法的代码。