Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an NSArray of NSString

Tags:

Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray:

NSMutableArray *arr = [[NSMutableArray alloc] init]; 

with elements such as "2", "4", "5", "1", "9", etc which are all NSString.

I'd like to sort the list in descending order so that the largest valued integer is highest in the list (index 0).

I tried the following:

[arr sortUsingSelector:@selector(compare:)]; 

but it did not seem to sort my values properly.

Can someone show me code for properly doing what I am trying to accomplish? Thanks!

like image 914
CodeGuy Avatar asked Dec 29 '10 23:12

CodeGuy


People also ask

How to sort an array of Object in js?

To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

How to order an array in JavaScript?

You can use the JavaScript sort() method to sort an array. The sort() method accepts an array as an argument and sorts its values in ascending order. Arrays are sorted in place which means the original array is modified. A new array is not created.


1 Answers

You should use this method:

[arr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 

in a NSArray or:

[arr sortUsingSelector:@selector(caseInsensitiveCompare:)]; 

in a "inplace" sorting NSMutableArray

The comparator should return one of this values:

  • NSOrderedAscending
  • NSOrderedDescending
  • NSOrderedSame
like image 95
HyLian Avatar answered Sep 29 '22 12:09

HyLian