vinylDeveloper
vinylDeveloper

Reputation: 707

How can I access properties of an object in an array of objects

I have an array of objects _schedule.games I want to display the Game property opponent in each game as I loop through the schedule.

    int x = 0;
    for (int i = 0; i < [_schedule.games count]; i++)
    {
        Game *game = [_schedule.games objectAtIndex:i];
        game.opponent = ((Game *) [_schedule.games objectAtIndex:i]).opponent;
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 100, 100)];

        [button setTitle:[NSString stringWithFormat:@"%@", game.opponent] forState:UIControlStateNormal];

        [_gameScrollList addSubview:button];

        x += button.frame.size.width;

    }

Upvotes: 0

Views: 92

Answers (1)

Lithu T.V
Lithu T.V

Reputation: 20021

1.

    Game *game = [_schedule.games objectAtIndex:i];

gives you the game instance inside the array,So no need to assign the property again as

game.opponent = ((Game *) [_schedule.games objectAtIndex:i]).opponent;

game.opponent has the value that is in the array object property and so you can call it directly as game.opponent .

2.

[NSString stringWithFormat:@"%@", game.opponent] says game.opponent is a string so no need to typecast it again as a NSString

So the method will be as

int x = 0;
for (int i = 0; i < [_schedule.games count]; i++)
{
    Game *game = (Game *)[_schedule.games objectAtIndex:i];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 100, 100)];
    [button setTitle:game.opponent forState:UIControlStateNormal];
    [_gameScrollList addSubview:button];
    x += button.frame.size.width;
}

Upvotes: 1

Related Questions