I have a NSArray of objects.
Those objects have an int attribute called “distance”. I would like to sort my array by distance.
Could someone please tell me how to do that ? I can’t understand how the sortUsingSelector or sortUsingDescriptor methods are working…
Thanks
I assume you’re using an NSMutableArray, because an NSArray is immutable.
When you sort something, you want the end result to be arranged as
How to define this
<=? There are 3 solutions in ObjC.1.
-sortUsingSelector:[arr sortUsingSelector:@selector(foo:)]means that its elements will be compared as*For example, to sort a list of strings case-insensitively, you use
[arr sortUsingSelector:@selector(caseInsensitiveCompare:)].2.
-sortUsingFunction:context:This is similar to
-sortUsingSelector:, but it uses a function pointer as input.[arr sortUsingFunction:funcptr context:ctx]means that its elements will be compared as3.
-sortUsingDescriptors:This is the most complicated one. It takes a list of NSSortDescriptors which describe the expected order of the properties. One basic example:
the descriptor tells the sort routine to “sort by the key
distancein ascending order”.Suppose there are 2 keys, integers
xascending then and stringsydescending, then you may writeand so on.
Note: * Actually you should only return -1, 0 or 1.