views:

36

answers:

1

I made a custom class. This is the h file

@interface Player : NSObject {
    NSString *name;
    NSNumber *points;
}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSNumber *points;

-(id) initWithName:(NSString *)n andPoints:(int)p;

@end

This is the m file

#import "Player.h"

@implementation Player
@synthesize name, points;

-(id) initWithName:(NSString *)n andPoints:(int)p
{
    self.name = n;
    self.points = [NSNumber numberWithInt:p];
    return self;
}
@end

Then I create several players, and assign them to one of two teams like this:

Player *p1 = [[Player alloc] initWithName:@"Joe" andPoints:5];
Player *p2 = [[Player alloc] initWithName:@"James" andPoints:5];
Player *p3 = [[Player alloc] initWithName:@"Jim" andPoints:5];

NSMutableArray *team1 = [[NSMutableArray alloc] initWithObjects:p1,p2,p3,nil];

Player *p4 = [[Player alloc] initWithName:@"Aaron" andPoints:7];
Player *p5 = [[Player alloc] initWithName:@"Anthony" andPoints:7];
Player *p6 = [[Player alloc] initWithName:@"Alex" andPoints:7];

NSMutableArray *team2 = [[NSMutableArray alloc] initWithObjects:p4,p5,p6,nil];

Then I put these two teams in another NSMutableArray like this:

NSMutableArray *allTeams = [[NSMutableArray alloc] initWithObjects:team1, team2, nil];

To display all the players and their points, I use this loop:

for (NSMutableArray *teamArray in allTeams) {
    for (Player *player in teamArray) {
        NSLog(@"%@: %@", [player name], [player points]);
    }
}

As it is, it will just show the players in the order they are added above.

I want to sort this array of teams by the team's points, which is just the sum of the points of each individual player in the team. Then when the loop runs to display all the players, the players in team2 will be displayed before team1.

What's the code to sort the allTeams array by team points? Do I need to use categories?

+4  A: 

It's actually going to be very simple. Do:

[allTeams sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"@sum.points" ascending:NO]]];

Hopefully that came out right. Typing code on an iPhone is a pain...

Dave DeLong
Got it backwards, the array operator comes first so @sum.points :) also note that the class convenience method is only available on iOS 4.0+ so it will crash on current iPads.
Jason Coco
Awesome, thanks! Is sorting by number of players just as easy?
awakeFromNib
@awakeFromNib yes, use `@count` instead of `@sum`
Dave DeLong
@Jason thanks for the correction. edited answer.
Dave DeLong