NSPredicate SELF CONTAINS[c] returns value contained in longer text first

Solution 1:

One way of solving this would be to apply the predicate to an NSSet instead of an NSArray. Something like this:

     NSSet *tempSet = [NSSet setWithArray:words];
     tempSet = [tempSet filteredSetUsingPredicate:predicate];
     resultsArray = [tempSet allObjects];

Hope this helps.

Solution 2:

Boom! I got it! All I had to add was NSSortDescriptor. Now it seems easy:

NSArray *words = [text componentsSeparatedByString:@" "];

    NSString *word1;
    NSString *word2;
    NSString *word3;
    NSPredicate *predicate;

    if (words.count == 1) {
        word1 = [NSString stringWithFormat:@"%@", [words objectAtIndex:0]];
        predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@ OR SELF LIKE[cd] %@", word1, word1];

    }
    else if (words.count == 2) {
        word1 = [NSString stringWithFormat:@"%@", [words objectAtIndex:0]];
        word2 = [NSString stringWithFormat:@"%@", [words objectAtIndex:1]];
        predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@ AND SELF CONTAINS[cd] %@", word1, word2];

    }
    else if (words.count == 3) {
        word1 = [NSString stringWithFormat:@"%@", [words objectAtIndex:0]];
        word2 = [NSString stringWithFormat:@"%@", [words objectAtIndex:1]];
        word3 = [NSString stringWithFormat:@"%@", [words objectAtIndex:2]];
        predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@ AND SELF CONTAINS[cd] %@ AND SELF CONTAINS[cd] %@", word1, word2,word3];

    }
    NSArray *sortedArray = [self.allItemsArray filteredArrayUsingPredicate:predicate];
    NSSortDescriptor *lengthSorter = [NSSortDescriptor sortDescriptorWithKey:@"length" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:lengthSorter];
    filteredTableData = [sortedArray sortedArrayUsingDescriptors:sortDescriptors];

It works the way I wanted now! But if you have any improvement suggestions, please share them!

Thank you