如何更改此代码以便NSMutableArray排序?

时间:2010-10-06 05:46:36

标签: objective-c cocoa-touch sorting object nsmutablearray

我做了一个自定义课程。这是h文件

@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

这是m文件

#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

然后我创建了几个玩家,并将它们分配给两个团队中的一个:

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];

然后我将这两个团队放在另一个NSMutableArray中:

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

要显示所有玩家及其积分,我会使用此循环:

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

实际上,它只会按照上面添加的顺序显示玩家。

我希望按球队的分数对这一系列球队进行排序,这只是球队中每个球员的得分总和。然后当循环运行以显示所有玩家时,team2中的玩家将在team1之前显示。

按团队积分对allTeams数组进行排序的代码是什么?我需要使用类别吗?

1 个答案:

答案 0 :(得分:4)

实际上这很简单。做:

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

希望这是正确的。在iPhone上键入代码很痛苦......