Iphone 动态创建多个类实例

Iphone 动态创建多个类实例,iphone,objective-c,xcode,Iphone,Objective C,Xcode,我的问题涉及一个2-4人可以玩的简单游戏。这是一款在iphone/ipod touch上玩的游戏,因此不需要联网。当游戏开始时,用户将选择要玩的玩家数量 对于每个玩家,我需要创建一个和一个玩家类的实例。我的问题是如何编码,以便只生成所需数量的类,并且它们的名称都不同。我想到了以下几点,但我知道这行不通 假设我有一个名为“playerNames”的数组,它存储游戏中玩家的名字 for (int i = 0; i < [playerNames count]; i++) { Play

我的问题涉及一个2-4人可以玩的简单游戏。这是一款在iphone/ipod touch上玩的游戏,因此不需要联网。当游戏开始时,用户将选择要玩的玩家数量

对于每个玩家,我需要创建一个和一个玩家类的实例。我的问题是如何编码,以便只生成所需数量的类,并且它们的名称都不同。我想到了以下几点,但我知道这行不通

假设我有一个名为“playerNames”的数组,它存储游戏中玩家的名字

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

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

     //other code

}
for(int i=0;i<[playerNames count];i++){
玩家*playeri=[[Player alloc]init];
//其他代码
}
我不能只是把“I”作为循环的计数器,然后得到四个名为player1、player2等的实例。我该怎么做


提前感谢您的帮助。

您不能动态创建变量实例-您需要一个集合来存储生成的播放器。C数组或NSMutableArray可以很好地工作。您可以将此集合添加到控制器或视图中,以便通过游戏访问玩家

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

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

     //other code

}
此外,您可能希望使用
autorelease
自动释放播放器,或者在
dealloc
方法中释放集合中的项目,以避免内存泄漏

下面是一些使用NSMutableArray的代码,我假设您会将其添加到类接口中(并在某处初始化,通常在
viewdiload
中)

-(void)CreatePlayers:(int)playerCount
{
对于(int i=0;i<[playerNames count];i++)
{
[播放器阵列插入对象:[[Player alloc]init]自动释放]
指数:i];
}
}

您不能像那样以编程方式准确命名变量

但是,您可以创建这些对象并将它们添加到NSMutableArray,然后稍后调用它们

如果您确实想将“PlayerN”名称与每个对象关联,请使用NSMutableDictionary。将播放器对象存储为键@“PlayerN”(NSString)的值

创建密钥的过程如下所示:

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

最基本的解决方案是将播放器存储在数组或字典中(键入播放器名称)。采用阵列方法:

// 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
属性访问每个播放器

关于设计的一句话——首先,你是否考虑过在你的
播放器
类中添加
名称
属性?在您捕获这些信息后,这里似乎是存储这些信息的自然场所。例如:

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 *newGame = [[Game alloc] init];
for(NSString *name) in playerNames) {
  [newGame addPlayerNamed:name];
}
您的
Game
类将封装玩家数组,而
addplayername
方法将封装创建新
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...
}