2014-04-06 18 views
0

我有一個數組,即時通訊使用顯示名稱,但是我希望顯示當前名稱和下一個名稱。在數組中顯示下一項

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

你試過'_index + 1%_players.count'嗎? (索引加一個mod數組) – BergQuester

+0

我該如何去使用它? – user3502233

回答

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; 
+0

嗨,謝謝你。然而,它在兩個位置出現錯誤時,index =(index + 1)%_players.count中的%給出錯誤,將二進制操作數無效。而且在nslog中它不能識別nextplayersname。有任何想法嗎? – user3502233

+0

index =(index + 1)%_players.count;這行是給我錯誤 – user3502233

+0

_index =(_index + 1)%_players.count;修正它需要一個_前索引和;最後抱歉需要擦幾次眼睛。 :) – user3502233

0

要遍歷一個NSArray您可能需要使用enumerateObjectsUsingBlock像:

[_players enumerateObjectsUsingBlock ^(id obj, NSUInteger idx, BOOL *stop){ 
    NSString * playerName = (NSString*)_players[_index++]; 
    NSLog(@" player %@", playerName); 
}]; 

docs

+0

這將在最後一次迭代中崩潰。 – vikingosegundo