0

I'm stuck with a little problem:

Player *player1;
Player *player2;
Player *player3;
Player *player4;

Inside Player class, I have a variable called, score. If I need to change all players score, I use this function:

for (int i = 1; i <= 4; i++)
{
    [self setValue:@"10,000" forKeyPath: [NSString stringWithFormat: @"player%i.score.text", i]];
}

Also in the Player class, I have a method called changeScorePosition. I would like to call this method for all "Players" in the game. How do I do this?

Monolo
  • 18,205
  • 17
  • 69
  • 103
BlackMouse
  • 4,442
  • 6
  • 38
  • 65

4 Answers4

1

Is player1 a global variable?

Instead, try creating an object to manage all players. This object could then easily iterate through all the players and update their score.

bbarnhart
  • 6,620
  • 1
  • 40
  • 60
1

You can put the players in an array and then call the correct player based on index using i (although it would need to start at 0).

NSArray *players = [NSArray arrayWithObjects: player1, player2, player3, player4, nil];


for (int i = 0; i < 4; i++)
{
  Player *currentPlayer = (Player *)[players objectAtIndex:i];
  // do whatever with your player here
}
Dima
  • 23,484
  • 6
  • 56
  • 83
1

It's better to create number of player like this,

NSMutableArray *playerArray = [[NSMutableArray alloc] init];

for (int i = 1; i <= 4; i++)
{
    Player *player = [{Player alloc] init];
    [playerArray addObject:player];
    [player release];
}

And call the methods like,

for (int i = 1; i <= 4; i++)
{
    [self setValue:@"10,000" forKeyPath: [NSString stringWithFormat: @"player%i.score.text", i]];
    [[playerArray  objectAtIndex:i-1] changeScorePosition];
}

Refer this link: access objective-c object by string name or variable

Community
  • 1
  • 1
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0

Thanks for the help. I change to code some, and found that I can do this:

[[self valueForKeyPath:[NSString stringWithFormat:@"player%i", i]] performSelector:@selector(playerDeclined)];
BlackMouse
  • 4,442
  • 6
  • 38
  • 65