0

I am having a problem that I think I am overcomplicating.

I need to make either an NSMutableArray or NSMutableDictionary. I am going to be adding at least two objects like below:

NSMutableArray *results = [[NSMutableArray alloc] init];

[results addObject: [[NSMutableArray alloc] initWithObjects: [NSNumber numberWithInteger:myValue01], @"valueLabel01", nil]];

This gives me the array I need but after all the objects are added I need to be able to sort the array by the first column (the integers - myValues). I know how to sort when there is a key, but I am not sure how to add a key or if there is another way to sort the array.

I may be adding more objects to the array later on.

Patrick
  • 6,495
  • 6
  • 51
  • 78

3 Answers3

2

Quick reference to another great answer for this question:

How to sort NSMutableArray using sortedArrayUsingDescriptors?

NSSortDescriptors can be your best friend in these situations :)

Community
  • 1
  • 1
Brayden
  • 1,795
  • 14
  • 20
  • No way!! I was searching for hours for this answer! Apparently I have to wait to mark as correct though. Cheers :) – Patrick Aug 28 '12 at 18:58
0

What you have done here is create a list with two elements: [NSNumber numberWithInteger:myValue01] and @"valueLabel01". It seems to me that you wanted to keep records, each with a number and a string? You should first make a class that will contain the number and the string, and then think about sorting.

Maciej Trybiło
  • 1,187
  • 8
  • 20
0

Doesn't the sortedArrayUsingComparator: method work for you? Something like:

- (NSArray *)sortedArray {
    return [results sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
    {
        NSNumber *number1 = [obj1 objectAtIndex:0];
        NSNumber *number2 = [obj2 objectAtIndex:0];
        return [number1 compare:number2]; }];
    }
Bruno Koga
  • 3,864
  • 2
  • 34
  • 45