简体   繁体   English

如何对1值为dec​​而1值为float的NSArray进行排序

[英]How to sort an NSArray where 1 value is dec and 1 value is float

My current project does a great deal of aggregation and one of the values I wanted to sort on is coming back in 2 flavors 我当前的项目进行了大量的汇总,我想排序的值之一又回到了两种风格

  1. My first source will return 0.9 / 1 / 1.1 我的第一个来源将返回0.9 / 1 / 1.1

  2. My second source will return 2.349823432 / 4.93432343 我的第二个来源将返回2.349823432 / 4.93432343

My question is 2 fold 我的问题是2折

  • What type should I set on my object to capture this value so sorting works correctly. 我应该在对象上设置哪种类型来捕获此值,以便正确进行排序。 I'm asking because I currently parse json and set these values manually. 我问是因为我目前解析json并手动设置这些值。

  • After the value is set what is the best way to sort w/ the information provided? 设置值后,对提供的信息进行排序的最佳方法是什么?

Thank you in advance 先感谢您

You might want to create a class to describe the values you are parsing, and define the sorting logic in that class. 您可能想要创建一个类来描述您正在解析的值,并在该类中定义排序逻辑。 A simple example, 一个简单的例子

@interface MyClass : NSObject {
    NSNumber *someNum;
        NSString *someString;
...
}

@implementation MyClass

- (NSComparisonResult)compareNums:(MyClass *)myClassObject {
    return [self.someNum compare:myClassObject.someNum];
}
- (NSComparisonResult)compareStringsDescending:(MyClass *)myClassObject {
    return -1 * [self.someString compare:myClassObject.someString];
}

... ...

Now you can sort many myClass objects by doing this in some viewcontroller: 现在,您可以在某些viewcontroller中对许多myClass对象进行排序:

NSArray *mySortedArray = [self.myOriginalArray sortedArrayUsingSelector:@selector(compareNums:)];

Hope this helps 希望这可以帮助

sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];

假设您在数组中有NSNumber ,而不是诸如NSValue东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM