I assume you are using NSMutableArray because NSArray is immutable.
When you sort something, you want the end result to be organized as
x1 <= x2 <= x3 <= x4 <= ... <= xN
How to determine this <= ? ObjC has 3 solutions.
1. -sortUsingSelector:
[arr sortUsingSelector:@selector(foo:)] means that its elements will be compared as *
x <= y is equivalent to [x foo:y] <= 0
For example, to sort the list of strings case-insensitively, you use [arr sortUsingSelector:@selector(caseInsensitiveCompare:)] .
2. -sortUsingFunction:context:
This is similar to -sortUsingSelector: but a function pointer is used as input. [arr sortUsingFunction:funcptr context:ctx] means that its elements will be compared as
x <= y is equivalent to funcptr(x, y, ctx) <= 0
3. -sortUsingDescriptors:
This is the most difficult question. It accepts a list of NSSortDescriptors that describe the expected order of properties. One basic example:
NSSortDescriptor* desc = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES]; [arr sortUsingDescriptors:[NSArray arrayWithObject:desc]]; [desc release];
the handle tells the sort routine to "sort by distance in ascending order."
Suppose there are 2 keys, the integers x incrementing, and then the lines y descending, then you can write
NSSortDescriptor* dx = [[NSSortDescriptor alloc] initWithKey:@"x" ascending:YES]; NSSortDescriptor* dy = [[NSSortDescriptor alloc] initWithKey:@"y" ascending:NO selector:@selector(caseInsensitiveCompare:)]; [arr sortUsingDescriptors:[NSArray arrayWithObjects:x, y, nil]]; [dx release]; [dy release];
etc.
Note: * In fact, you should only return -1, 0, or 1.