views:

38

answers:

2

Is the best way of doing what i'm doing? goodThingX, badThingX and nothin are 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;
}

i.e. When the the todayNothing has some text, I want to hide 6 labels, and display the nothing label, else the opposite. I woudn't have bothered to optimize this, but probably there are going to be more labels than the 6 right now..

+2  A: 

You can place them all in an array at init or awakeFromNib or similar making it easier to iterate over later.

@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;
}

...and then later you use a loop like this

for (int i=0; i<NUM_THINGS; i++)
  theThings[i].hidden = YES;
epatel
You mean `return self;`?
KennyTM
@KennyTM ah yes of course...
epatel
I'm using NSArray instead of `UIView *theThings[NUM_THINGS];` and i'm having problems iterating over the loop, i'm trying `[theThings objectAtIndex:1];` Am i doing it right?
Swizzy
Use fast enumeration (for-in loop) for `NSArray`!
KennyTM
+1  A: 

Firstly, you have something known as "boolean variable".

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;

Second, it's better to use an array or NSArray to store all the good- and badThings. (See epatel's answer.)

KennyTM
This brings down the code length by half, so i'm going to use this for now. Meanwhile I'm trying to change epatel's code for NSArray..
Swizzy