Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Sort an array of string

Tags:

I have to sort an array of objects by a property of the objects that is a string. How can I do this?

like image 375
Andrea Mario Lufino Avatar asked Apr 28 '11 15:04

Andrea Mario Lufino


People also ask

How to sort array string in Objective c?

For just sorting array of strings: sorted = [array sortedArrayUsingSelector:@selector(compare:)]; For sorting objects with key "name": NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; sorted = [array sortedArrayUsingDescriptors:@[sort]];

How does arrays sort() work?

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

How do I create an NSArray in Objective C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

How to order by 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.


2 Answers

you need to use

-[NSArray sortedArrayUsingSelector:] 

or

-[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter.

here's a link to the answer Sort NSArray of date strings or objects

like image 117
Jason Cragun Avatar answered Sep 27 '22 19:09

Jason Cragun


For just sorting array of strings:

sorted = [array sortedArrayUsingSelector:@selector(compare:)]; 

For sorting objects with key "name":

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; sorted = [array sortedArrayUsingDescriptors:@[sort]]; 

Also, instead of compare: you can use:

  • caseInsensitiveCompare:

  • localizedCaseInsensitiveCompare:

like image 24
Borzh Avatar answered Sep 27 '22 21:09

Borzh