0

In my app, i have a search bar in my contact list page tableview. now my code searches the list based on any letter even if the search text is at the middle of the firstname or lastname. But i want it to search only from the beginning. For example., the word "sh" should pull only "Shiva", "Sheela", etc., but not "sathish", "suresh" etc., can anyone help me on this?

and my code is

- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText
{
//---if there is something to search for---
if ([searchText length] > 0)
{
    isSearchOn = YES;
    canSelectRow = YES;
    self.ContactTableview.scrollEnabled = YES;
    searchTextValue = searchText;
    [searchResult removeAllObjects];

    for (NSString *str in ContactArray)
    {
        NSRange range = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if(range.location != NSNotFound)
        {
            if(range.length > 0)//that is we are checking only the start of the names.
            {
                [searchResult addObject:str];
            }
        }
    }
}
else
{
    //---nothing to search---
    isSearchOn = NO;
    canSelectRow = NO;
    self.ContactTableview.scrollEnabled = YES;
    //SearchBar.showsCancelButton = NO;
    [TitleBarLabel setText:@"All Contacts"];

}
[ContactTableview reloadData];
}
4

1 回答 1

2

尝试使用谓词,在下面的代码中替换您的值。

 NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@",@"A"];
    NSArray *a = [NSArray arrayWithObjects:@"AhfjA ", @"test1", @"Test", @"AntA", nil];
    NSArray *b = [a filteredArrayUsingPredicate:p];
    NSLog(@"--%@",b);

运单:-

(
    AntA,
    AntA
)
于 2013-06-27T15:15:57.873 回答