Search code examples
iosobjective-cnsstringuisearchdisplaycontrollernsrange

Search for any characters in an NSString


I have the following code to search an NSString:

for (NSDictionary *obj in data) {
        NSString *objQuestion = [obj objectForKey:@"Question"];
        NSRange dataRange = [objQuestion rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (dataRange.location != NSNotFound) {
            [filteredData addObject:obj];
        }
    }

This works fine, but there is a problem. If objQuestion is: "Green Yellow Red" and I search for "Yellow Green Red", the object will not show up as my search is not in the correct order.

How would I change my code so that no matter what order I search the words in, the object will show?


Solution

  • You should be breaking your search text into words and search each word.

    NSArray *wordArray= [searchText componentsSeparatedByString: @" "];
    for (NSDictionary *obj in data) {
        NSString *objQuestion = [obj objectForKey:@"Question"];        
        BOOL present = NO;
        for (NSString *s in wordArray) {
            if (s) {                
                NSRange dataRange = [objQuestion rangeOfString:s options:NSCaseInsensitiveSearch];
                if (dataRange.location != NSNotFound) {
                   present = YES;
                }
            } 
        }
        if (present) {
            [filteredData addObject:obj];
        }
    }