Objective c 使用for循环来alloc、init和设置多个对象的属性?

Objective c 使用for循环来alloc、init和设置多个对象的属性?,objective-c,for-loop,iteration,Objective C,For Loop,Iteration,有没有一种方法可以使用for循环来执行下面的代码,而不必键入重复 bar1 = [[UIView alloc] init]; bar1.backgroundColor = [UIColor blueColor]; [self addSubview:bar1]; bar2 = [[UIView alloc] init]; bar2.backgroundColor = [UIColor blueColor]; [self addSubview:bar

有没有一种方法可以使用for循环来执行下面的代码,而不必键入重复

    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];

您可以使用C数组:

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

或者,如果您想保留这些单独的属性,可以使用“stringly-typed”并使用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]];
  }
}


但还有一些其他选择。希望这足以让你开始

@AlanZeino在评论中我还说可以使用
NSMutableArray
。这足以演示该形式,对于固定大小的数组来说也很好。ARC会把它清理干净的。哦,对不起。我误解了您页面上的消息。非常感谢-您不必使用此代码手动创建IVAR,这太好了。如何使用NSMutableArray而不是C数组?此外,这是否可以通过属性而不是IVAR来实现?
- (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]];
  }
}
- (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];
  }
}