我正在制作一个迷你高尔夫记分卡应用程序中的'赢家屏幕'。我有两个存储1)的数组。球员的名字和2)。他们的分数。
playerNameArray = [[NSMutableArray alloc]initWithObjects:playerOneName.text, playerTwoName.text, playerThreeName.text, playerFourName.text, playerFiveName.text, playerSixName.text, nil];
scoreArray = [[NSMutableArray alloc]initWithObjects:playerOneStat.text, playerTwoStat.text, playerThreeStat.text, playerFourStat.text, playerFiveStat.text, playerSixStat.text, nil];
我能够找到得分最低的球员的名字:
int winner = [[scoreArray valueForKeyPath:@"@min.intValue"] intValue];
NSLog(@"the winner scored %d", winner);
NSString *string = [NSString stringWithFormat:@"%d", winner];
NSUInteger indexOfTheObject = [scoreArray indexOfObject:string];
NSString *playerString = [playerNameArray objectAtIndex:indexOfTheObject];
NSLog(@"The winner name is %@", playerString);
如果只有一个玩家,则有效,但如果有两个或更多玩家获得相同的最低分,那么它只能显示数组顺序中第一个玩家的名字。如何修改代码以创建共享相同分数的获奖者列表/数组?
答案 0 :(得分:2)
由于你有两个“并行”数组,也许最简单的就是有一个循环,如下所示:
for (int i = 0 ; i != scoreArray.count ; i++) {
if (scoreArray[i].intValue == winner) {
NSLog(@"Winner %@ at index %d.", playerNameArray[i], i);
}
}
如果您遵循更传统的方法并创建了一个代表玩家的对象,比如说,
@interface Player : NSObject
@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) int score;
-(id)initWithName:(NSString*)name andScore:(int)score;
@end
然后您就可以使用谓词进行搜索,并一次性检索所有获胜者。
答案 1 :(得分:1)
我会使用NSMutableDictionary
代替两个数组。
//NSMutableDictionary to store player scores rather than two arrays
NSMutableDictionary *players = [NSMutableDictionary new];
//Each player name is a key with their score stored as an NSNumber
[players setObject:@(10) forKey:@"John"];
[players setObject:@(15) forKey:@"Tim"];
[players setObject:@(20) forKey:@"Phil"];
[players setObject:@(17) forKey:@"Kurt"];
[players setObject:@(19) forKey:@"Cory"];
[players setObject:@(10) forKey:@"Robert"];
//Find the lowest score out of the bunch
NSNumber *theLowestScore = [[players allValues] valueForKeyPath:@"@min.intValue"];
//There could be multiple lowest score players so this will get everyone that is associated with the lowest score
NSArray *playersWithLowestScores = [players allKeysForObject:theLowestScore];
//Print out the players name who have the lowest score
[playersWithLowestScores enumerateObjectsUsingBlock:^(NSString *playerName, NSUInteger idx, BOOL *stop) {
NSLog(@"%@", playerName);
}];
答案 2 :(得分:1)
只需在代码中添加for循环即可。其他的事情很好。但是没有测试过代码。检查格式错误:
int winner = [[scoreArray valueForKeyPath:@"@min.intValue"] intValue];
NSLog(@"the winner scored %d", winner);
NSString *string = [NSString stringWithFormat:@"%d", winner];
for (int i=0; i<scoreArray.count; i++) {
if ([scoreArray[i] isEqualToString:string]) {
[indices addObject:@(i)];
}
}
NSLog(@"%@",indices);
for (int i=0; i<indices.count; i++) {
//print all player names with lowest score
NSLog(@"The winner(s) are:");
NSLog(@"%@,",playerNameArray[indices[i].intValue]);
}