1

I having problems to sort an NSArray of custom objects. The NSArray has to be sorted by a method that returns an int value (so it's not an object's attribute) and by an attribute that belongs to the object.

So suppose that my array contains an NSArray of PolygonObject. Each PolygonObject has plenty of attributes, and one of them is 'height'. Beside that, I want to sort the array by calculating the area of each polygon. So I want to sort the array by 'area' (using method that calculates the area) and by height (simple attribute of the object).

I know how to sort an NSArray using a method (sortedArrayUsingComparator, sortedArrayUsingSelector...) and using a key (NSSortDescriptor), but I have no idea about how to sort it using both.

How can I do it?

Girish
  • 4,692
  • 4
  • 35
  • 55
Stacky
  • 103
  • 1
  • 7

3 Answers3

2

Use sortedArrayUsingDescriptors: and pass an array of 2 sort descriptors. The first one will do the primary sorting, and the second refines that one. The sort descriptors could be created with sortDescriptorWithKey:ascending:comparator: to allow you to write your own comparator for calculating the area.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
1

I would recalculate area when you set polygon parameters and then use the field in sorting instead of calling area method to recalculate area every time a polygon object is compared to another object, but that's up to you.

You might want to have a look at How to sort NSMutableArray using sortedArrayUsingDescriptors which has examples of sorting.

Especially look at the part using 2 NSSortDescriptors.

Basically you create one sort descriptor for each parameter on which you want to sort, then put them into an array and sort using that array. If I'm not mistaken for fields you just provide the field name as a string (see the linked answer).

Community
  • 1
  • 1
stefanB
  • 77,323
  • 27
  • 116
  • 141
1

NSArray exposes "sortUsingDescriptors" method. This method can use an array of keys and produce sorted array.

I would generate multiple sort descriptors and add them to an array for. Use this array with sortUsingDescriptors method

Ref: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/sortedArrayUsingDescriptors:

vrrathod
  • 1,230
  • 2
  • 18
  • 28