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

前端 未结 2 392
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 03:36

I have a class (from NSObject) that contains:

NSString name
int      position
float    speed

I then create an array (NSM

相关标签:
2条回答
  • 2021-01-06 03:59
    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;
    }
    
    0 讨论(0)
  • 2021-01-06 04:20

    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.

    0 讨论(0)
提交回复
热议问题