2013-03-20 65 views
4

我正在创建一个简单的文字游戏,其中显示了所有用户的活动匹配。我想按照从最近到最近最近活动的顺序对这些匹配数组进行排序,但与玩家轮流关联的唯一时间戳属性是GKTurnBasedParticipant ... GKTurnBasedMatch的属性没有有用的排序属性。如何按最近激活的方式对GKTurnBasedMatch进行排序?

GKTurnBasedMatch有一个GKTurnBasedParticipant对象的数组作为属性,所以我肯定能够想出某种解决方案,但我想不出任何不会太杂乱和低效的东西。有没有什么办法可以像NSPredicate这样简单的方法来深入研究每个参与者阵列,查看最新的时间戳并一次筛选所有匹配?

回答

3

我没有NSPredicate为基础的解决方案,或者可能是任何你想象中的优雅,但我遇到了同样的问题,并写了我自己的解决方案,并没有那么糟糕。

我的解决方案是一个游戏,只能有两个参与者,那么相应的修改,但这里是我最后使用的代码:

[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是一个自定义类我为我的游戏(其中具有GKTurnBasedMatchmatch属性),并且实例方法localPlayersTurn返回BOOL,指示它是否是本地参与者的轮到。

然后,我在一个类别写了GKTurnBasedMatch一个lastMove方法:

- (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; 
} 

同样,这仅适用于共两个参与者,但会很容易地修改其中任意数量。

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

+0

干得漂亮。我的快速创可贴解决方案是在匹配数据中包装一个'lastMove'NSDate值,并在每次转动时更新它,但是您的分类方法绝对更清晰,更简单。谢谢一堆! – cowfaboo 2013-04-01 18:17:48

+0

请注意,如果玩家超时,这将返回错误的日期。例如。如果Player2超时,它将再次成为Player1的转向。现在,即使Player1的lastTurnDate更近,此方法也会返回Player2的lastTurnDate。 – Phlibbo 2017-02-07 19:19:04

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]]; 
}]; 
相关问题