开发者

Iterating object manipulation or altering multiple objects at once

开发者 https://www.devze.com 2022-12-17 03:32 出处:网络
Is the best way of doing what i\'m doing? goodThingX, badThingX and nothin are UILabels. NSString *todayNothing = [[todayArray objectAtIndex:0] objectForKey: @\"nothing\"];

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..


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;


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消