How to sort NSMutableArray objects by a member of its class, which is an int or float

I have a class (from NSObject ) that contains:

 NSString name int position float speed 

Then I create an array ( NSMutableArray ) of objects from this class. Then I would like to sort the array by the speed value, which is a float .

I initially had float as NSNumber and int as NSInteger , and I successfully sorted 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 when I use int instead of NSInteger , the above code does not work. Is there a lower level command that I should use to do sorting? Thanks!

+4
source share
2 answers

As in the opposite, I would 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 can collapse if - else if - else with the ternary operator: test ? trueValue : falseValue or if speed is an object with the compare: method (for example, NSNumber), you can simply return [[self speed] compare:[otherObject speed]]; )

Then you can sort by

 [myMutableArray sortUsingSelector:@selector(compareSpeed:)]; 

As suggested by George in the commentary, you can also achieve your goal using the NSSortDescriptor ; if you are targeting 10.6, you can also use blocks and sortUsingComparator:(NSComparator)cmptr .

+5
source
 int compareSpeed( id p1 , id p2 , void *unused ) { return p1->speed > p2->speed ? 1 : p1->speed < p2->speed : -1 : 0; } 

Although you really should make the above method of your class as follows:

 -(int) compareSpeed:(id)inOtherObjectOfSameType { return self->speed > inOtherObjectOfSameType->speed ? 1 : self->speed < inOtherObjectOfSameType->speed : -1 : 0; } 
+1
source

Source: https://habr.com/ru/post/1307802/


All Articles