NSMutableArray sorting - case insensitive
Asked Answered
B

2

25

I am sorting an NSMutableArray as follows:

    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:str_key ascending:bool_asc_desc] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedArray;
    sortedArray = [ads_printers_array sortedArrayUsingDescriptors:sortDescriptors];

The problem is that this is case sensitive, and I would like to make it case insensitive. How can I do that? I tried reading the docs and found something like this:

sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:str_key ascending:bool_asc_desc selector: @selector(caseInsensitiveCompare)] autorelease];

However, I have no idea what I should be putting in the selector argument. Thanks!

Bikaner answered 20/6, 2012 at 7:13 Comment(4)
Checkout following post: https://mcmap.net/q/271962/-i-want-to-sort-an-array-using-nssortdescriptorWeen
Thank you, for anyone interested the selector method that I used is (localizedCaseInsensitiveCompare:). Cheers!Bikaner
possible duplicate of I want to sort an array using NSSortDescriptorNica
Perfect, thank you. (Is anything in Objective-C straightforward..?!)Theologize
V
49
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:str_key 
    ascending:YES selector:@selector(caseInsensitiveCompare:)];

ads_printers_array = [ads_printers_array sortedArrayUsingDescriptors:[NSArray 
    arrayWithObject:sortDescriptor]];
Vulture answered 22/4, 2013 at 13:23 Comment(0)
R
1

For Swift, do the following:

let sortDescriptor = NSSortDescriptor(key: sortDescriptorKey, ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))

Riproaring answered 3/10, 2017 at 22:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.