2011-07-18 32 views
0

我有一個代碼塊,將六個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中的字符串的值嗎?

我知道這是很多要看,但我真的很感激任何幫助或建議在這裏。

謝謝了。

+1

我剛調整了標題。希望那樣更好。 – dutsnekcirf

回答

2

問題是你創建for循環的方式。正確的語法是:for(initialize; test; update)。從1迭代變量i 6,你應該使用:

for(int i = 1; i <= 6; i++) { 
    [self addPlayerToBoard:i]; 
} 

當您使用!===經營者的物體上,你是比較對象的指針。這意味着如果兩個對象完全是同一個對象,那麼它們將只是相同的,而不僅僅是等價的。要確定兩個對象是否相同,您應該使用[object1 isEqualTo:object2]。如果您知道對象將是NSString,則應該使用[string1 isEqualToString:string2],因爲它會更快。

if (![[playerDictionary valueForKey:@"PlayerName"] isEqualToString:@"Enter your name"]) { 
    ... 
} 
+0

非常感謝你! – dutsnekcirf

相關問題