如何按最近最活跃的方式对GKTurnBasedMatch进行排序?

时间:2013-03-20 15:29:43

标签: iphone ios nspredicate game-center gamekit

我正在创建一个带有菜单屏幕的简单文字游戏,其中我显示了所有用户的活动匹配。我想按照从最近到最近最不活跃的顺序对这个匹配数组进行排序,但与轮换的玩家相关联的唯一时间戳属性是GKTurnBasedParticipant的属性... GKTurnBasedMatch没有有用的排序属性。

GKTurnBasedMatch有一个GKTurnBasedParticipant个对象作为属性,所以我当然能够提出某种解决方案,但我想不出任何不会有的东西。真的很乱,效率低下。有没有像NSPredicate这样简单的东西可以用在这样的情况下深入到每个参与者数组中,查看最新的时间戳并一次性对所有匹配进行排序?

2 个答案:

答案 0 :(得分:3)

我没有基于NSPredicate的解决方案,或者可能是你所希望的任何优雅的东西,但我遇到了同样的问题并编写了我自己的解决方案,实际上并没有那么糟糕。< / p>

我的解决方案是一个只能有两个参与者的游戏,所以相应地进行修改,但这是我最终使用的代码:

[myGamesArray sortUsingComparator:^NSComparisonResult(CHGame *game1, 
                                                      CHGame *game2) {

    if (YES == [game1 localPlayersTurn] && NO == [game2 localPlayersTurn]) {
        return NSOrderedAscending;
    } else if (NO == [game1 localPlayersTurn] && YES == [game2 localPlayersTurn]) {
        return NSOrderedDescending;
    }

    NSDate *lm1 = [game1.match lastMove];
    NSDate *lm2 = [game2.match lastMove];
    if (lm1 != nil && lm2 != nil) {
        return [lm1 compare:lm2];
    }

    return NSOrderedSame;

}];

其中CHGame是我为游戏构建的自定义类(具有GKTurnBasedMatch match属性),实例方法localPlayersTurn返回BOOL }表明是否是本地参与者的回合。

然后我在lastMove上的类别中编写了GKTurnBasedMatch方法:

- (NSDate *)lastMove {
    GKTurnBasedParticipant *localParticipant, *otherParticipant;
    NSDate *lastMove;

    for (GKTurnBasedParticipant *participant in self.participants) {
        if (YES == [participant.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]) {
            localParticipant = participant;
        } else {
            otherParticipant = participant;
        }
    }

    if (localParticipant == self.currentParticipant) {
        lastMove = otherParticipant.lastTurnDate;
    } else {
        lastMove = localParticipant.lastTurnDate;
    }

    return lastMove;
}

同样,这仅适用于两个参与者,但对于任何数量的参与者都很容易修改。

希望这有帮助,即使它并不完全符合您的要求。

答案 1 :(得分:0)

按当前参与者的最后一轮

对基于回合的匹配进行排序
[GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error)
 {
     NSString *descriptorKey = @"currentParticipant.lastTurnDate";

     NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:descriptorKey
                                                                      ascending:NO];

     NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:@[sortDescriptor]];
 }];



按创建日期对基于回合的匹配进行排序

[GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error)
 {
     NSString *descriptorKey = @"creationDate";

     NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:descriptorKey
                                                                      ascending:NO];

     NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:@[sortDescriptor]];
 }];
相关问题