我有一个用于显示名称的数组,但我希望显示当前名称和下一个名称。
IE
如果其玩家1参加游戏,则显示
玩家1开始吧
玩家2准备好开始
这是我到目前为止只显示当前字符串和循环直到游戏结束。
if (_index == _players.count) {
_index = 0;
}
NSString * playerName = (NSString*)_players[_index++];
// NSString * nextplayerName = (NSString*)_players[_index++];
NSLog(@" player %@", playerName);
self.turnlabel.text = playerName;
如何显示数组中的下一个项目,但仍然按顺序继续按顺序继续显示数组?
答案 0 :(得分:2)
你很亲密。在获得下一个玩家名字后,你不应该增加_index,因为你还没有进入该玩家。
if (_index == _players.count)
{
_index = 0;
}
//Get the player at the current index
NSString * playerName = (NSString*)_players[_index];
//advance the index to the next play, and "wrap around" to 0 if we are at the end.
index = (index+1) %_players.count
//load the next player's name, but don't increment _index again.
NSString *nextplayerName = (NSString*)_players[_index];
NSLog(@" player %@. nextPlayer = %@", playerName, nextplayerName);
self.turnlabel.text = playerName;
答案 1 :(得分:0)
要遍历NSArray,您可能希望使用enumerateObjectsUsingBlock
,如:
[_players enumerateObjectsUsingBlock ^(id obj, NSUInteger idx, BOOL *stop){
NSString * playerName = (NSString*)_players[_index++];
NSLog(@" player %@", playerName);
}];
请参阅docs。