這個最基本的解決辦法是將玩家存儲數組或字典(鍵控的玩家名稱)。以數組方式:
// 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...
}