如何在for循环中创建NSArray

时间:2012-06-30 19:22:35

标签: iphone objective-c ios cocoa-touch sdk

如何通过在for循环中执行以下代码来缩短以下代码?

NSArray *images = [NSArray arrayWithObjects:
                         [UIImage imageNamed:@"z1.png"],
                         [UIImage imageNamed:@"z2.png"],
                         [UIImage imageNamed:@"z3.png"],
                         [UIImage imageNamed:@"z4.png"],
                         [UIImage imageNamed:@"z5.png"],
                         [UIImage imageNamed:@"z6.png"],
                         [UIImage imageNamed:@"z7.png"],
                         [UIImage imageNamed:@"z8.png"],
                         [UIImage imageNamed:@"z9.png"],
                         [UIImage imageNamed:@"z10.png"],
                         [UIImage imageNamed:@"z11.png"],
                         [UIImage imageNamed:@"z12.png"],
                         [UIImage imageNamed:@"z13.png"],
                         [UIImage imageNamed:@"z14.png"],
                         [UIImage imageNamed:@"z15.png"],
                         [UIImage imageNamed:@"z16.png"],
                         [UIImage imageNamed:@"z17.png"],
                         [UIImage imageNamed:@"z18.png"],
                         [UIImage imageNamed:@"z19.png"],
                         nil];

6 个答案:

答案 0 :(得分:11)

魔术在NSMutableArray中,就像评论中提到的@Teak一样。实际上,所有容器类都有一个可变版本,例如NSStringNSDictionaryNSSet等。

NSMutableArray *images = [NSMutableArray array];

for (NSUInteger i = 1; i <= 19; i++) {
    NSString *imageName = [NSString stringWithFormat:@"z%d.png", i];
    [images addObject:[UIImage imageNamed:imageName];
}

答案 1 :(得分:4)

如果你不介意停止动画,你可以从iOS 5开始执行以下操作:

UIImage *myAnimatedImage = [UIImage animatedImageNamed:@"z" duration:10];

它将自动搜索图像并为其添加数字。警告是你不能像UIImageView中那样停止动画图像。

答案 2 :(得分:2)

您需要使用NSMutableArray。但是,如果不可变性很重要,您可以在最后将结果放在NSArray

NSMutableArray *workingArray = [NSMutableArray array];
for (int i = 0; i < NUM_IMAGES; i++) {
    [workingArray addObject:[UIImage imageName:[NSString stringWithFormat:@"z%d.png", i]];
}

NSArray *images = [NSArray arrayWithArray:workingArray];

答案 3 :(得分:1)

NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:19];

for(int i = 1; i <=19; i++)
    [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"z%d.png, i]]];

答案 4 :(得分:1)

 NSMutableArray *arrImage = [NSMutableArray  arrayWithCapacity:0];
 for(int i = 1; i<= 19;i++)
 {
    [arrImage  addObject:[UIImage imageNamed:[NSString stringWithFormat:@"z%d.png",i]]];
 }

答案 5 :(得分:1)

加载动画UIImage,为您处理文件名。然后从中检索图像数组。

NSArray* images = [UIImage animatedImageNamed:@"z" duration:1].images;