2012-11-07 42 views
2

有没有办法使用for循环来执行下面的代码?使用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]; 

回答

2

你可以使用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]; 
    } 
} 

,但也有一些其他的选择。希望这足以让你开始!

+2

为什么是C数组? –

+0

@AlanZeino在评论中我也说过可以使用'NSMutableArray'。这足以证明这种形式,并且适用于固定大小的阵列。 ARC将清理它。 – justin

+0

哦,对不起。我误解了您网页上的讯息。 – pasawaya