Gurinder Batth
Gurinder Batth

Reputation: 663

How to get same name results first in search list iOS

enter image description here

Hello everyone I need your help. I want that like in image if I search carrot listing should show Carrot first like the element having same name show first and if element contains these text list after that is that possible

 NSString *predicateString;

            NSString * tempString;

            if (string.length > 0) {
                tempString = [NSString stringWithFormat:@"%@%@",textField.text, string];
            } else {
                tempString = [textField.text substringToIndex:[textField.text length] - 1];
            }

                predicateString = [NSString stringWithFormat:@"SELF.title contains [cd] \"%@\" ", tempString];

            NSLog(@"Ingredent Array  :- %@ ",allIngrediantArr);

            NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
            if (allIngrediantArr.count>0) {
                searchFilterdArr = [NSMutableArray arrayWithArray:[allIngrediantArr filteredArrayUsingPredicate:predicate]];
            }

Upvotes: 0

Views: 54

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15768

You can filter the searchFilterdArr array by comparing the range of search string.

  NSString *searchStr = @"carrot";  
  NSArray *searchFilterdArr = [[NSArray alloc ] initWithObjects:@{@"title":@"baby carrot"},@{@"title":@"baby purple carrot"},@{@"title":@"carrot"}, nil];
  NSLog(@"%@",searchFilterdArr);
  id mySort = ^(NSDictionary * obj1, NSDictionary * obj2){
    return [[obj1 valueForKey:@"title"] rangeOfString:searchStr].location > [[obj2 valueForKey:@"title"] rangeOfString:searchStr].location;
  };
  NSArray * sortedMyObjects = [searchFilterdArr sortedArrayUsingComparator:mySort];
  NSLog(@"%@",sortedMyObjects);

searchFilterdArr

{ title = "baby carrot"; }, { title = "baby purple carrot"; }, { title = "carrot"; }

sortedMyObjects

{ title = "carrot"; }, { title = "baby carrot"; }, { title = "baby purple carrot"; }

Upvotes: 1

Anbu.Karthik
Anbu.Karthik

Reputation: 82769

you can use in the alternate

BEGINSWITH

predicateString = [NSString stringWithFormat:@"SELF.title BEGINSWITH [cd] \"%@\" ", tempString];

CONTAINS || BEGINSWITH

if you want the both (contains || Beginswith), then use

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                      @"(SELF.title BEGINSWITH [cd] \"%@\") OR (SELF.title CONTAINS [cd] \"%@\")", tempString, tempString];

MATCHES || BEGINSWITH

  NSPredicate *predicate = [NSPredicate predicateWithFormat:
                      @"(SELF.title BEGINSWITH [cd] \"%@\") OR (SELF.title MATCHES [cd] \"%@\")", tempString, tempString];

see the NSPredicate string comparison

enter image description here

Upvotes: 2

Related Questions