1

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.

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

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

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Population" ascending:NO] autorelease]; 

with

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:NO] autorelease]; 

This Works.. Because Name is String. Please help me out How can I sort this array with numeric value.

Thank you in advance.

1 Answer 1

1

A quick run of your code gives to following output which seems right for me:

2010-07-29 16:32:59.774 test[93035:207] (
    {
    Area = 554445;
    Name = Kolkatta;
    Population = 874544541;
},
    {
    Area = 324544;
    Name = Chennai;
    Population = 454154412;
},
    {
    Area = 345475;
    Name = Delhi;
    Population = 412541245;
}
)

I just replaced your return with: NSLog(@"%@", [sorted subarrayWithRange:range]);

Cheers...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.