Naresh
Naresh

Reputation: 363

How to display searchresults in alphabetical order in ios

Hi in my application I have a to search few elements and the result have to show in tableview. For example if the elements are

NS1,NSE2,NAse3,NWe3,Nxw,NB22 like this if I search for N then the data have to display as such below

NAse3
NB22
NSE2
NS1
NWe3
Nxw. 

Please let me know how to implement this.

Now I am using the below code I am performing the search.

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if([array count]!=0){
        array2=[[NSMutableArray alloc]initWithCapacity:0 ];
        for(NSMutableDictionary *data in array){
            r = [[data objectForKey:@"Product"] rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
            if(r.location != NSNotFound){
                 if(r.location== 0)
                     [array2 addObject:data];
            }
       }
    }
}

Upvotes: 1

Views: 272

Answers (3)

Pratyusha Terli
Pratyusha Terli

Reputation: 2343

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if([array count]!=0)
    {
        array2=[[NSMutableArray alloc]initWithCapacity:0];

        for(NSMutableDictionary *data in array)
        {
            r = [[data objectForKey:@"Product"] rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];

            if(r.location != NSNotFound)
            {
                 if(r.location== 0)
                 [array2 addObject:data];
             }
       }
       NSSortDescriptor *sortDis = [[NSSortDescriptor alloc] initWithKey:@"Product"
                      ascending:YES selector:@selector(localizedStandardCompare:)];
      [array2 sortUsingDescriptors:[NSArray arrayWithObject:sortDis]];
    }
}

Upvotes: 2

Nimit Parekh
Nimit Parekh

Reputation: 16864

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"your Key"
                                              ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

Using custom comparator-methods is possible Have a look at the documentation.

Upvotes: 0

Muruganandham K
Muruganandham K

Reputation: 5331

try this to sort your results:

array2 = [array2 sortedArrayUsingComparator:^(id a, id b) {
    return [a compare:b options:NSNumericSearch];
}];

Upvotes: 1

Related Questions