如何在ios中按字母顺序显示搜索结果

时间:2013-11-07 09:38:54

标签: ios objective-c

您好我的应用程序中有一个搜索少量元素,结果必须显示在tableview中。例如,如果元素是

NS1,NSE2,NAse3,NWe3,Nxw,NB22如果我搜索N那么数据必须如下所示

NAse3
NB22
NSE2
NS1
NWe3
Nxw. 

请告诉我如何实现这一点。

现在我正在使用以下代码执行搜索。

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

尝试这样对结果进行排序:

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

答案 2 :(得分:0)

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

使用自定义比较器方法可以查看documentation