Evgeniy S
Evgeniy S

Reputation: 1484

How to filter array with NSPredicate for combination of words

[filteredArray filterUsingPredicate:
   [NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] %@", searchText]];

filteredArray contains simple NSStrings. [hello, my, get, up, seven, etc...];

It will give all strings that begin with searchText.

But if string will be a combination of words like "my name is", and searchText = name. What would a NSPredicate look like to achieve this?

UPDATE: And how would it have to be if i want to a result with searchText = name, but not with searchText = ame? Maybe like this:

 [filteredArray filterUsingPredicate:
       [NSPredicate predicateWithFormat:
        @"self BEGINSWITH[cd] %@ or self CONTENTS[cd] %@", 
        searchText, searchText]];

But it should first display the strings that begin with searchText and only after those which contain searchText.

Upvotes: 4

Views: 4342

Answers (2)

Mundi
Mundi

Reputation: 80265

[NSPredicate predicateWithFormat:@"self CONTAINS[cd] %@", searchText];

EDIT after expansion of question

NSArray *beginMatch = [filteredArray filteredArrayUsingPredicate:
  [NSPredicate predicateWithFormat:
    @"self BEGINSWITH[cd] %@", searchText]];
NSArray *anyMatch = [filteredArray filteredArrayUsingPredicate:
  [NSPredicate predicateWithFormat:
    @"self CONTAINS[cd] %@", searchText]];

NSMutableArray *allResults = [NSMutableArray arrayWithArray:beginMatch];
for (id obj in anyMatch) {
   if (![allResults containsObject:obj]) {
      [allResults addObject:obj];
   }
}
filteredArray = allResults;

This will have the results in the desired order without duplicate entries.

Upvotes: 5

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

EDIT Actually beginsWith check from start of string to search string length. if exact match found then its filtered

if u have name game tame lame
search Text : ame
filtered text would be: none

contains also check from start of string to search string length but if found start, middle or end exact search string then it is filtered.

if u have name game tame lame
search Text : ame
filtered text would be: name game tame lame because all has ame

[NSPredicate predicateWithFormat:@"self CONTAINS '%@'", searchText];

Upvotes: 2

Related Questions