scribbler2309
scribbler2309

Reputation: 153

Objective C search sort search results by search string first letter

Looking through the docs and having a hard time figuring out if there is a simple method to order search results according to the first letter of the search query. i.e I would like to show all search results for the letter 'n' but bring entries beginning with 'n' to the front of the array. The database is large and the only way I can think to do this is to filter a sorted alphabetical array by taking out all 'n' entries and adding them to the beginning of the alphabetical array. Thanks

Upvotes: 0

Views: 324

Answers (1)

Larme
Larme

Reputation: 26066

You could use a block comparator:

NSString *prefix = [@"n" uppercaseString];
NSArray *sortedArray = [arrayNotSorted sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
{
    if ([[(NSString*)a uppercaseString] hasPrefix:prefix] && ![[(NSString*)b uppercaseString] hasPrefix:prefix])
        return NSOrderedAscending;
    else if (![[(NSString*)a uppercaseString] hasPrefix:prefix] && [[(NSString*)b uppercaseString] hasPrefix:prefix])
        return NSOrderedDescending;
    else
        return [a caseInsensitiveCompare:b];
}];

Tested with (output NSLog):

>ArrayNotSorted: (
    Hello,
    NLow,
    nHi,
    Bo,
    "What?",
    NBA
)
>SortedArray: (
    NBA,
    nHi,
    NLow,
    Bo,
    Hello,
    "What?"
)

Here a few things:
• I casted "a" and "b", in case you may be using other objects than NSString. For example, if objects are of type:

ClassCustom
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int someValue;

You can do:
NSString *aObjectToCompare = [(ClassCustom *)a name]; instead of (NSString *)a.

• I used also caseInsensitiveCompare: at the end. But you can use compare: if more appropriated.
• I used the upperCaseString method to avoid the "n" or "N" issue. But you may also erase it, and maybe add other "if/else" if you want to priotorize the uppercase or the lowercase.

Upvotes: 1

Related Questions