Mano
Mano

Reputation: 740

Searching the initial letter of a word using searchBar

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

Upvotes: 0

Views: 322

Answers (1)

user2455507
user2455507

Reputation:

try with predicates,in below code replace your values.

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

O/P:-

(
    AntA,
    AntA
)

Upvotes: 2

Related Questions