I have a class (from NSObject) that contains:
NSString name
int position
float speed
I then create an array (NSMutableArray) of objects from this class. I would like to then sort the array by the ‘speed’ value, which is a float.
I initially has the float value as an NSNumber and the int as NSInteger, and I was successfully sorting with:
[myMutableArray sortUsingFunction:compareSelector context:@selector(position)];
where myMutableArray is my array of objects.
here is the function:
static int compareSelector(id p1, id p2, void *context) {
SEL methodSelector = (SEL)context;
id value1 = [p1 performSelector:methodSelector];
id value2 = [p2 performSelector:methodSelector];
return [value1 compare:value2];
}
Now that I am using int instead of NSInteger, the above code does not work. Is there a more low-level command that I should be using to execute the sort? Thank!
Similar to drawnonward, I’d suggest adding a comparison method to your class:
(You could collapse the
if–else if–elseusing the ternary operator:test ? trueValue : falseValue, or ifspeedis an object with acompare:method (such as NSNumber), you could justreturn [[self speed] compare:[otherObject speed]];.)You can then sort by
As suggested by Georg in a comment, you can also achieve your goal using
NSSortDescriptor; if you’re targeting 10.6, you can also use blocks andsortUsingComparator:(NSComparator)cmptr.