如何通过其类的成员(即int或float)对NSMutableArray对象进行排序 [英] How to sort an NSMutableArray of objects by a member of its class, that is an int or float
问题描述
我有一个来自NSObject
的类,其中包含:
I have a class (from NSObject
) that contains:
NSString name
int position
float speed
然后我从该类创建对象的数组(NSMutableArray
).然后,我想按'speed'值对数组进行排序,该值是float
.
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
.
最初,我将float
值作为NSNumber
,将int
值作为NSInteger
,并且我成功地使用了:
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)];
其中myMutableArray
是我的对象数组.
这是函数:
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];
}
现在我使用的是int
而不是NSInteger
,上面的代码不起作用.我应该使用更底层的命令来执行排序吗?谢谢!
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!
推荐答案
类似于drawonward,我建议在您的课程中添加一个比较方法:
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;
}
}
(您可以使用三元运算符test ? trueValue : falseValue
折叠if
-else if
-else
,或者如果speed
是具有compare:
方法的对象(例如NSNumber),则可以只是return [[self speed] compare:[otherObject speed]];
.)
(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]];
.)
然后您可以排序
[myMutableArray sortUsingSelector:@selector(compareSpeed:)];
正如Georg在评论中建议的那样,您也可以使用NSSortDescriptor
实现目标;如果您的目标是10.6,则还可以使用块和
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
.
这篇关于如何通过其类的成员(即int或float)对NSMutableArray对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!