iosobjective-cbinary-treebinary-search-treeprefix-tree

What is the efficient way to search trough NSArray


I have NSStrings in my array:

i[0] = axxx
i[1] = axyz
i[2] = axxy
i[3] = abcd

I want to pass a search string to find all needed strings. For example if I pass "ax" then it will return 3 strings, if I pass "axx" then it will return 2 string.

Performance is critical here as well. The method should look like this:

- (NSArray *)searchString:(NSString *)search; 

Noramlly I use NSPredicate, but this time I need to use maybe Prefix Tree or Binary Tree, I am not sure but it should be faster. Any suggestion or links to implementation.


Solution

  • Hope this solution will satisfy you.

    - (NSArray *)searchString:(NSString *)search{
    
        NSIndexSet *indexes = [dataArray indexesOfObjectsPassingTest:
                               ^BOOL (id obj, NSUInteger i, BOOL *stop) {
                                   NSString *myObj = obj;
                                   return [myObj containsString:search];
                               }];
        NSArray *results = [dataArray objectsAtIndexes:indexes];
    
        return results;
    
    }