简体   繁体   中英

Sort an NSMutableArray / Dictionary with several objects

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.

Quick reference to another great answer for this question:

How to sort NSMutableArray using sortedArrayUsingDescriptors?

NSSortDescriptors can be your best friend in these situations :)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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