Search code examples
iphoneiosnspredicateuisearchdisplaycontroller

Searching NSArray for substring in a specific way


I have a UISearchDisplay Controller setup, and it is working to filter values, but I was wondering if someone could help me with a little bit more advanced way of filtering the results.

Say my array was: { American example, Eric, Different-Eric }

If the user searched "Eri", the results should be { Eric, Different-Eric } because is should only return results where a word starts with the substring, not if its in the center of a word (American).

It should also check if '-' could be a ' ', and visaversa. So the substring 'Different-Eri' would also search the substring 'Different Eri', and in reverse too.

If you need any more clarification, I'd be happy to answer. I was just wondering if there was a good way to go about this.

Current code:

NSPredicate *resultPredicate = [NSPredicate 
                                    predicateWithFormat:@"SELF.comname contains[cd] %@",
                                    searchText];

    searchResults = [[birdsArray filteredArrayUsingPredicate:resultPredicate] mutableCopy];

Solution

  • I actually solved this by making some changes to my Custom Object and the search predicate. A lot simpler of a solution than I was previously thinking.

    In my Custom Object I made 2 properties, and had the Getters method return a 'first name' and 'last name' respectively, which basically broke the full string into the first word and last word, using ' ' or '-' as word deliminators.

    The my search predicate simply became:

    NSPredicate *spacePredicate = [NSPredicate 
                                       predicateWithFormat:@"SELF.comname BEGINSWITH[cd] %@ OR SELF.lastname BEGINSWITH[cd] %@",
                                       searchText, searchText];
    
        searchResults = [[birdsArray filteredArrayUsingPredicate:spacePredicate] mutableCopy];
    

    I used 'BEGINSWITH' instead of contains to make sure the start of the word matched the substring.

    The end :), hope it helps someone.