开发者

How to change this code so the NSMutableArray is sorted?

开发者 https://www.devze.com 2023-01-19 08:02 出处:网络
I made a custom class. This is the h file @interface Player : NSObject { NSString *name; NSNumber *points;

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;
}
@en开发者_开发问答d

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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消