这个最基本的解决办法是将玩家存储数组或字典(键控的玩家名称)。以数组方式:
// 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...
}