Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray sorting - case insensitive

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!

like image 284
Kevin Avatar asked Jun 20 '12 07:06

Kevin


2 Answers

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

ads_printers_array = [ads_printers_array sortedArrayUsingDescriptors:[NSArray 
    arrayWithObject:sortDescriptor]];
like image 145
karthika Avatar answered Dec 30 '22 15:12

karthika


For Swift, do the following:

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

like image 28
ChrisJF Avatar answered Dec 30 '22 14:12

ChrisJF