Problem with sorting NSDictionary

Posted by Stas Dmitrenko on Stack Overflow See other posts from Stack Overflow or by Stas Dmitrenko
Published on 2011-01-12T17:19:39Z Indexed on 2011/01/12 17:53 UTC
Read the original article Hit count: 299

Filed under:
|
|

Hello. I need to sort a NSDictionary of dictionaries. It looks like:

{//dictionary
        RU = "110.1"; //key and value
        SG = "150.2"; //key and value
        US = "50.3"; //key and value
    }

Result need to be like:

 {//dictionary
            SG = "150.2"; //key and value
            RU = "110.1"; //key and value
            US = "50.3"; //key and value
        }

I am trying this:

@implementation NSMutableDictionary (sorting)

-(NSMutableDictionary*)sortDictionary
{
    NSArray *allKeys = [self allKeys];
    NSMutableArray *allValues = [NSMutableArray array];
    NSMutableArray *sortValues= [NSMutableArray array];
    NSMutableArray *sortKeys= [NSMutableArray array];

    for(int i=0;i<[[self allValues] count];i++)
    {
        [allValues addObject:[NSNumber numberWithFloat:[[[self allValues] objectAtIndex:i] floatValue]]];   
    }



    [sortValues addObjectsFromArray:allValues];
    [sortKeys addObjectsFromArray:[self allKeys]];
    [sortValues sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"floatValue" ascending:NO] autorelease]]];

    for(int i=0;i<[sortValues count];i++)
    {
        [sortKeys replaceObjectAtIndex:i withObject:[allKeys objectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]]]];
        [allValues replaceObjectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]] withObject:[NSNull null]];
    }
    NSLog(@"%@", sortKeys);
    NSLog(@"%@", sortValues);
    NSLog(@"%@", [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]);
    return [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys];
}

@end

This is the result of NSLog: 1)

{
SG,
RU,
US
}

2)

{
150.2,
110.1,
50.3
}

3)

{
            RU = "110.1";
            SG = "150.2";
            US = "50.3";
        }

Why is this happening? Can you help me with this problem?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about sorting