迭代对象操作或一次更改多个对象

时间:2010-01-17 18:16:22

标签: objective-c iphone

做我正在做的事情的最佳方式是什么? goodThingXbadThingXnothin是UILabels。

NSString *todayNothing = [[todayArray objectAtIndex:0] objectForKey: @"nothing"];
if (todayNothing!=NULL) {
    goodThing1.hidden = YES;
    goodThing2.hidden = YES;
    goodThing3.hidden = YES;
    badThing1.hidden = YES;
    badThing2.hidden = YES;
    badThing3.hidden = YES;
    nothing.text = todayNothing;
    nothing.hidden = NO;
} else {
    goodThing1.hidden = NO;
    goodThing2.hidden = NO;
    goodThing3.hidden = NO;
    badThing1.hidden = NO;
    badThing2.hidden = NO;
    badThing3.hidden = NO;
    nothing.hidden = YES;
}

即。当todayNothing有一些文字时,我想隐藏6个标签,并显示nothing标签,否则相反。我没有打算优化这个,但可能会有比6更多的标签..

2 个答案:

答案 0 :(得分:2)

您可以将它们全部放在initawakeFromNib或类似的数组中,以便以后进行迭代。

@class MyThing {

   UIView *theThings[NUM_THINGS]; // ...or use an NSArray if you like that

}
@end

- (id)init // maybe awakeFromNib would be a better place for UI elements
{
  self = [super init];
  if (self) {
    theThings[0] = goodThing1;
    theThings[1] = goodThing2;
    theThings[2] = goodThing3;
    :
  }
  return self;
}

...然后你会使用像这样的循环

for (int i=0; i<NUM_THINGS; i++)
  theThings[i].hidden = YES;

答案 1 :(得分:1)

首先,你有一个叫做“布尔变量”的东西。

NSString *todayNothing = [[todayArray objectAtIndex:0] objectForKey: @"nothing"];
BOOL todayNothing_has_something = (todayNothing!=nil); // YES if todayNothing!=nil, NO otherwise
goodThing1.hidden = todayNothing_has_something;
goodThing2.hidden = todayNothing_has_something;
goodThing3.hidden = todayNothing_has_something;
badThing1.hidden = todayNothing_has_something;
badThing2.hidden = todayNothing_has_something;
badThing3.hidden = todayNothing_has_something;
if (todayNothing)
  nothing.text = todayNothing;
nothing.hidden = ! todayNothing_has_something;

其次,最好使用数组或NSArray来存储所有good - 和badThing s。 (见epatel的答案。)