How can I sort a NSArray by NSSortDiscriptor?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kapil Choubisa
    New Member
    • Sep 2009
    • 47

    How can I sort a NSArray by NSSortDiscriptor?

    Hi All, I am new in iPhone development. I need your help in sorting NSArray.

    in this Code I am assigning values to the MyData. this is a NSArray variable.

    Code:
    NSMutableArray *MyArray=[NSMutableArray array];
    
    [MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:314564454],@"Population", @"Mumbai",@"Name", [NSNumber numberWithInt:415452],@"Area",nil]];
    
    [MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys[NSNumber numberWithInt:454154412],@"Population", @"Chennai",@"Name", [NSNumber numberWithInt:324544],@"Area",nil]];
    
    [MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:874544541],@"Population", @"Kolkatta",@"Name", [NSNumber numberWithInt:554445],@"Area",nil]];
    
    [MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:412541245],@"Population", @"Delhi",@"Name", [NSNumber numberWithInt:345475],@"Area",nil]];
    
    self.MyData = [NSArray arrayWithArray:MyArray];
    Now I need top 3 Cities with the Highest Population Information.

    So I had Write Following Code.,

    Code:
    NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Population" ascending:NO] autorelease]; 
    NSArray *sorted = [self.MyData sortedArrayUsingDescriptors: 
        [NSArray arrayWithObject:sorter]];   
    
    NSRange range = NSMakeRange(0,3); 
    return [sorted subarrayWithRange:range];
    But it is not working. The same code works if I replace the following
    Code:
    NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Population" ascending:NO] autorelease];
    With
    Code:
    NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:NO] autorelease];
    It Works...
    Because Name is String. Please help me out How can I sort this array with numeric value.

    Thank you in advance.
Working...