1
我是iPhone開發新手。我需要你對NSArray進行排序的幫助。如何通過NSSortDiscriptor對NSArray進行排序?
在這段代碼中,我正在給MyData賦值。這是一個NSArray變量。
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];
現在我需要排名前三位的城市人口信息最高。
於是我只好寫下面的代碼,
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];
但它無法正常工作。如果我
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:NO] autorelease];
該工程.. 因爲名稱是字符串替換以下
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"Population" ascending:NO] autorelease];
相同的代碼工作。 請幫我解決我怎樣才能排序這個數組的數值。
預先感謝您。