I have to sort an array of objects by a property of the objects that is a string. How can I do this?
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]];
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.
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.
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.
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With