2013-08-19 191 views
0

我有一个对象数组_schedule.games我想在每个游戏中显示游戏属性对手,因为我循环调度。如何访问对象数组中的对象的属性

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; 

    } 
+0

你为什么在相同的添加所有按钮位置。您在设置框架中不使用x。所以所有按钮都添加在相同的位置。 –

+0

在控制台中打印game.opponent,重写这一行有什么用处。 'game.opponent =((Game *)[_schedule.games objectAtIndex:i])。opponent;'如果你可以直接访问游戏.opponent –

+0

@NishantTyagi我忘了将“x”改回去,它会打印(null)我两个按钮*数组有2个对象 – vinylDeveloper

回答

1

1.

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

为您提供了数组中的游戏实例,所以没必要的财产再次为

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

game.opponent分配有一个数组中的价值对象属性,所以你可以直接调用它作为game.opponent

2.

[NSString stringWithFormat:@"%@", game.opponent]game.opponent是一个字符串,所以没有必要再强制转换它作为NSString

因此该方法会随着

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; 
} 
+0

在循环中增加x的意义是什么?在上面的代码中没有使用它的任何地方。代码中的CGRect(20,0,100,100)应替换为CGRect(x + 20,0,100,100);使其生效。 – CodenameLambda1

+0

我独自回答了这个问题。你的观点是正确的,增量应该用于x或y在设置适当的框架其他按钮重叠 –

+0

@ CodenameLambda1我使用x,只是做了一个改变,忘了改回来时我已经发布。事实证明,我并没有正确地初始化我的游戏,因此game.opponent为null。不过,我会接受你的答案,因为它比我的方法更简洁,没有我不需要的额外代码。谢谢 – vinylDeveloper