开发者

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

开发者 https://www.devze.com 2023-02-05 23:17 出处:网络
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

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

  2. My second source will return 2.349823432 / 开发者_开发百科4.93432343

My question is 2 fold

  • 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.

  • 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:

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

Hope this helps


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

Assuming that you have NSNumber's in the array and not something like NSValue or so

0

精彩评论

暂无评论...
验证码 换一张
取 消