2009-07-24 85 views
0

我的問題涉及2-4人可以玩的簡單遊戲。這是一款在iPhone/iPod touch上播放的遊戲,因此不需要網絡連接。當遊戲開始時,用戶將選擇將玩的玩家人數。即時創建多個類實例

對於我需要創建的每個玩家和Player類的實例。我的問題是我如何編寫代碼,以便只有所需數量的類被創建,並且它們都被命名爲不同。我想到了以下內容,但我知道這是行不通的。

假設我有一個名爲「playerNames」的數組,存儲玩家在遊戲中的名字。

for (int i = 0; i < [playerNames count]; i++) { 

    Player *playeri = [[Player alloc] init]; 

    //other code 

} 

我不能只是把「我」在那裏作爲計數器的循環,並得到四個實例進行命名PLAYER1,player2等我該怎麼辦呢?

在此先感謝您的幫助。

回答

2

您無法即時創建變量實例 - 您需要一個集合來存儲結果播放器。一個C數組或NSMutableArray可以很好地工作。您可以將此集合添加到您的控制器或視圖中,讓玩家可以通過遊戲進行訪問。

此外,您可能需要使用autorelease自動釋放球員或可替換地釋放集合中的項目在dealloc方法以避免內存泄漏。

下面是使用一個NSMutableArray,我已經假設你會添加到您的類接口(和初始化的地方,通常在viewDidLoad)一些代碼

-(void) CreatePlayers:(int)playerCount 
{ 
    for(int i = 0; i < [playerNames count]; i++) 
    { 
     [playersArray insertObject:[[[Player alloc] init] autorelease] 
         atIndex:i]; 
    } 
} 
0

你叫不出名的變量編程這樣。

然而,您可以創建這些對象並將它們添加到NSMutableArray,然後再調用它們。

如果您確實想將「PlayerN」名稱與每個對象關聯,請使用NSMutableDictionary。將播放器對象存儲爲鍵值@「PlayerN」(一個NSString)。

創建密鑰可以做這樣的:

NSString *key = [NSString stringWithFormat:@"Player%d", i]; 
0

這個最基本的解決辦法是將玩家存儲數組或字典(鍵控的玩家名稱)。以數組方式:

// assume we have an NSArray property, players 
NSMutableArray *tempPlayers = [NSMutableArray arrayWithCapacity:[playerNames count]]; 
for (NSString *name in playerNames) { 
    Player *player = [[Player alloc] init]; 
    [tempPlayers addObject:player]; 
    [player release]; 
} 
self.players = tempPlayers; 

你可以通過調用objectAtIndex:現在訪問來自players屬性中的每個球員。

關於設計的一句話 - 首先,您是否考慮過將name屬性添加到您的Player類中?這似乎是一個自然的地方來存儲這些信息後,你已經捕獲它。例如:

for (NSString *name in playerNames) { 
    // you might also have a designated initializer 
    // e.g. [[Player alloc] initWithName:name] 

    Player *player = [[Player alloc] init]; 
    player.name = name; 
    [tempPlayers addObject:player]; 
    [player release]; 
} 

總的來說,這是最簡單的工作,是我現在要做的。但是,在未來...

在某些時候,你可能會發現自己引入某種Game類的代表您的用戶創建的每個新遊戲。這將是一個自然的地方來存儲您的播放器陣列和將允許你建立一個更具凝聚力的接口,例如:

Game *newGame = [[Game alloc] init]; 
for(NSString *name) in playerNames) { 
    [newGame addPlayerNamed:name]; 
} 

Game類將封裝的球員陣列和addPlayerNamed方法將封裝過程創建一個新的Player並將其存儲在該數組中,從而使您的控制器代碼在過程中變得更簡單(並且意圖顯示)。

的這另一個好處是它給你能夠在你的應用程序訪問這些數據,而不是它在這個特定的控制器捆綁的方式。你可以實現某種類似單身的訪問「currentGame」。所以,現在

Game *newGame = [[Game alloc init]; 
.. // configure game as above 
[Game setCurrentGame:newGame]; 

,每當你需要訪問當前遊戲(或播放器)的信息:當然不是一個真正的單身人士,但像這樣將工作做好

// in some other controller 
Game *currentGame = [Game currentGame]; 
for(Player *player in currentGame.players) { 
    // etc... 
}