The most basic solution for this would be to store the players in either an array or a dictionary (keyed on the player name). Taking the array approach:
// 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;
You can now access each player from the players
property by calling objectAtIndex:
.
A word on design - firstly, have you considered adding a name
property to your Player
class? This seems like a natural place to store this information after you've captured it. For example:
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];
}
Overall this is the simplest thing that works and is all I would do for now. However, in the future...
At some point, you may find yourself introducing some kind of Game
class that represents each new game your user creates. This would be a natural place to store your array of players and would allow you to build a more cohesive interface, for instance:
Game *newGame = [[Game alloc] init];
for(NSString *name) in playerNames) {
[newGame addPlayerNamed:name];
}
Your Game
class would encapsulate the array of players and the addPlayerNamed
method would encapsulate the process of creating a new Player
and storing it in that array, making your controller code much simpler (and intention-revealing) in the process.
Another benefit of this is it gives you a way of being able to access this data throughout your app rather than having it tied up in this particular controller. You could implement some kind of singleton-like access to a "currentGame". Not a true singleton of course, but something like this would work well:
Game *newGame = [[Game alloc init];
.. // configure game as above
[Game setCurrentGame:newGame];
So now, whenever you need access to current game (or player) information:
// in some other controller
Game *currentGame = [Game currentGame];
for(Player *player in currentGame.players) {
// etc...
}