我有一個代碼塊,將六個Player對象添加到六個Seat UIView對象中。我使用存儲在NSMuteableDictionary中的數據添加它們。有沒有更好的方法來做到這一點?想要使用一個循環,但它打破
這裏是它的外觀的時刻:
MoneyCentralAppDelegate *delegate = (MoneyCentralAppDelegate *) [[UIApplication sharedApplication] delegate];
//add player1
NSMutableDictionary *player1Dictionary = [[delegate appDataDictionary] valueForKey:@"Player1"];
Player *player1 = [[Player alloc] initWithFrame:CGRectMake(0,0,0,0)];
player1.playerName = [player1Dictionary [email protected]"PlayerName"];
player1.avatar = [UIImage imageNamed:[player1Dictionary valueForKey:@"Avatar"]];
[seat1 setAlpha:1];
[seat1 addSubView:player1];
//add player2
NSMutableDictionary *player2Dictionary = [[delegate appDataDictionary] valueForKey:@"Player2"];
if ([player2Dictionary valueForKey:@"PlayerName"] != @"Enter your name") {
Player *player2 = [[Player alloc] initWithFrame:CGRectMake(0,0,0,0)];
player2.playerName = [player2Dictionary [email protected]"PlayerName"];
player2.avatar = [UIImage imageNamed:[player2Dictionary valueForKey:@"Avatar"]];
[seat2 setAlpha:1];
[seat2 addSubView:player2];
}
//And so on for another 4 more players...
是不是有辦法通過使用一個循環來簡化這個代碼?我試過以下,但它不起作用:
for (int i=1; i=6, i++) {
[self addPlayerToBoard:i];
}
- (void) addPlayerToBoard:(int)playerNumber {
MoneyCentralAppDelegate *delegate = (MoneyCentralAppDelegate *) [[UIApplication sharedApplication] delegate];
NSMutableDictionary *playerDictionary;
NSString *thePlayer;
Seat *seat;
switch (playerNumber) {
case 1:
thePlayer = @"Player1";
seat = seat1;
break;
case 2:
thePlayer = @"Player2";
seat = seat2:
break;
case 3:
//and so on to 6
}
playerDictionary = [[delegate appDataDictionary] valueForKey:thePlayer];
if ([playerDictionary valueForKey:@"PlayerName"] != @"Enter your name") {
Player *newPlayer = [[Player alloc] initWithFrame:CGRectMake(0,0,0,0)];
newPlayer.playerName = [playerDictionary valueForKey:@"PlayerName"];
newPlayer.avatar = [UIImage imageName:[playerDictionary valueForKey:@"Avatar"]];
[seat setAlpha:1];
[seat addSubView:newPlayer];
}
}
據我可以看到這個代碼是好的。它編譯時沒有任何錯誤或警告,但是當我嘗試啓動一款新遊戲時,該應用只會在嘗試運行該代碼時凍結。
也只是作爲一個側面問題,if語句檢查PlayerName!= @「輸入你的名字」的值是否顯示爲真,不管是什麼,因爲我每次都會結束六名玩家。這是錯誤的方式來檢查nsmutabledictionary中的字符串的值嗎?
我知道這是很多要看,但我真的很感激任何幫助或建議在這裏。
謝謝了。
我剛調整了標題。希望那樣更好。 – dutsnekcirf