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

走远了吗. 提交于 2019-12-03 21:20:08

问题


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!


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/2700797/how-to-sort-an-nsmutablearray-of-objects-by-a-member-of-its-class-that-is-an-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!