I have a class (from NSObject
) that contains:
NSString name
int position
float speed
I then create an array (NSM
int compareSpeed( id p1 , id p2 , void *unused ) {
return p1->speed > p2->speed ? 1 : p1->speed < p2->speed : -1 : 0;
}
Although really you should make the above a method of your class like so:
-(int) compareSpeed:(id)inOtherObjectOfSameType {
return self->speed > inOtherObjectOfSameType->speed ? 1 : self->speed < inOtherObjectOfSameType->speed : -1 : 0;
}
Similar to drawnonward, I'd suggest adding a comparison method to your class:
- (NSComparisonResult)compareSpeed:(id)otherObject
{
if ([self speed] > [otherObject speed]) {
return NSOrderedDescending;
} else if ([self speed] < [otherObject speed]) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}
(You could collapse the if
-else if
-else
using the ternary operator: test ? trueValue : falseValue
, or if speed
is an object with a compare:
method (such as NSNumber), you could just return [[self speed] compare:[otherObject speed]];
.)
You can then sort by
[myMutableArray sortUsingSelector:@selector(compareSpeed:)];
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 and sortUsingComparator:(NSComparator)cmptr.