fxfuture
fxfuture

Reputation: 1950

Use a for loop to alloc, init and set properties for multiple objects?

Rather than having to type repetitions, is there a way to use a for loop to execute the below code?

    bar1 = [[UIView alloc] init];
    bar1.backgroundColor = [UIColor blueColor];
    [self addSubview:bar1];

    bar2 = [[UIView alloc] init];
    bar2.backgroundColor = [UIColor blueColor];
    [self addSubview:bar2];

    bar3 = [[UIView alloc] init];
    bar3.backgroundColor = [UIColor blueColor];
    [self addSubview:bar3];

    bar4 = [[UIView alloc] init];
    bar4.backgroundColor = [UIColor blueColor];
    [self addSubview:bar4];

    bar5 = [[UIView alloc] init];
    bar5.backgroundColor = [UIColor blueColor];
    [self addSubview:bar5];

Upvotes: 2

Views: 611

Answers (1)

justin
justin

Reputation: 104698

You could use a C array:

enum { NBars = 5 };

@implementation MONClass
{
  UIView * bar[NBars]; // << your ivar. could also use an NSMutableArray.
}

- (void)buildBars
{
  for (int i = 0; i < NBars; ++i) {
    bar[i] = [[UIView alloc] init];
    bar[i].backgroundColor = [UIColor blueColor];
    [self addSubview:bar[i]];
  }
}

or you can use an NSArray:

@interface MONClass ()
@property (nonatomic, copy) NSArray * bar;
@end

@implementation MONClass

- (void)buildBars
{
  NSMutableArray * tmp = [NSMutableArray new];
  enum { NBars = 5 };
  for (int i = 0; i < NBars; ++i) {
    UIView * view = [[UIView alloc] init];
    view.backgroundColor = [UIColor blueColor];
    [tmp addObject:view];
    [self addSubview:view];
  }
  self.bar = tmp;
}

or if you want to hold on to those individual properties, you could go 'stringly-typed' and use KVC:

- (void)buildBars
{
  enum { NBars = 5 };
  // if property names can be composed
  for (int i = 0; i < NBars; ++i) {
    UIView * theNewView = ...;
    [self setValue:theNewView forKey:[NSString stringWithFormat:@"bar%i", i]];
  }
}

or

- (void)buildBars
  // else property names
  for (NSString * at in @[
    // although it could use fewer characters,
    // using selectors to try to prevent some errors
    NSStringFromSelector(@selector(bar0)),
    NSStringFromSelector(@selector(bar1)),
    NSStringFromSelector(@selector(bar2)),
    NSStringFromSelector(@selector(bar3)),
    NSStringFromSelector(@selector(bar4))
  ]) {
      UIView * theNewView = ...;
      [self setValue:theNewView forKey:at];
  }
}

but there are a few other options. Hope that's enough to get you started!

Upvotes: 2

Related Questions