1

Suppose I have following data in my game. I have developed game in cocos2d.

Name    Score
Sagar   10000
Amit     2000
Vishal     90

Above data is stored in plist file.

Plist has an array as root.

Within that there are 10 dictionary.

Each dictionary has two values:

  • String values - Name
  • Number value - score

When I use

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

I want to sort this mutable array by score.

Is it possible?

halfer
  • 19,824
  • 17
  • 99
  • 186
sagarkothari
  • 24,520
  • 50
  • 165
  • 235

3 Answers3

8

Use a sort descriptor:

NSSortDescriptor * sortByScore = [[[NSSortDescriptor alloc] initWithKey:@"Score" ascending:NO] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortByScore];
NSArray * sorted = [x sortedArrayUsingDescriptors:descriptors];
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
1

See [NSMutableArray sortUsingDescriptors:], [NSMutableArray sortUsingComparator:] and so on. NSMutableArray provides several methods for sorting. In this case, I'd use the descriptor method if I needed to be compatible before 10.5 and the comparator method for Snow Leopard apps.

Chuck
  • 234,037
  • 30
  • 302
  • 389
1

I believe on the iPhone, your options are

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

and

- (void)sortUsingSelector:(SEL)comparator;

there is a bunch of decent info on it here: http://www.cocoadev.com/index.pl?SortUsingSelector

EDIT: whoops! saw cocos2d and assumed it was an iPhone question.

Kenny Winker
  • 11,919
  • 7
  • 56
  • 78
  • No, No. It is an iPhone question. I am using plist for score storing. Question is about plist & array with plist. No need to worry. I am studying your given link. – sagarkothari Nov 05 '09 at 22:53