在nsmutablearray中排序

时间:2009-11-05 22:38:56

标签: objective-c sorting nsarray

假设我的游戏中有以下数据。我用cocos2d开发了游戏。

Name    Score
Sagar   10000
Amit     2000
Vishal     90

以上数据存储在plist文件中。

Plist有一个数组作为root。

其中有10个字典。

每个字典都有两个值:

  • 字符串值 - 名称
  • 数值 - 得分

当我使用

NSMutableArray *x=[[NSMutableArray alloc] initWithContentsOfFile:@"Sagar.plist"];

我想按分数对这个可变数组进行排序。

有可能吗?

3 个答案:

答案 0 :(得分:8)

使用排序描述符:

NSSortDescriptor * sortByScore = [[[NSSortDescriptor alloc] initWithKey:@"Score" ascending:NO] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortByScore];
NSArray * sorted = [x sortedArrayUsingDescriptors:descriptors];

答案 1 :(得分:1)

请参阅[NSMutableArray sortUsingDescriptors:][NSMutableArray sortUsingComparator:]等。 NSMutableArray提供了几种排序方法。在这种情况下,如果我需要在10.5之前兼容并使用Snow Leopard应用程序的比较器方法,我将使用描述符方法。

答案 2 :(得分:1)

我相信iPhone,您的选择

- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;

- (void)sortUsingSelector:(SEL)comparator;

这里有很多不错的信息: http://www.cocoadev.com/index.pl?SortUsingSelector

编辑:哎呀!看到cocos2d,并认为这是一个iPhone问题。

相关问题