objective-c - 使用 for 循环为多个对象分配、初始化和设置属性?

标签 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: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]];
  }
}

或者您可以使用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;
}

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

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

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

关于objective-c - 使用 for 循环为多个对象分配、初始化和设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262028/

相关文章:

c - 简单的 for 循环在 C 中不起作用

java - 反向迭代 LinkedHashMap

ios - 在另一个类 objective-c 中保存一个类的实例

iphone - 放置 popViewController 动画 : in viewDidLoad or viewDidAppear will not work

c++ - for循环的初始化和增量部分中的逗号如何工作?

mysql - 使用变量和 while 存在的情况下迭代 mysql select 语句

c - 将用户输入的 char 存储为变量时出错

java - 迭代后跳过一行

ios - Xcode 5新文档将注释注释与属性或方法放在同一行

iphone - 动态检查类是否通过 respondsToSelector : 响应选择器