迭代文件名

时间:2014-01-23 17:41:29

标签: ios objective-c

我正在尝试遍历文件名,这些文件名都具有相同的名称,并且末尾有一个递增的数字。我现在有这样的事情:

 int i;
 NSString * imagename[i];
 for (i = 0; i < 49; i++) {
 photo = [MWPhoto photoWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]   pathForResource:imagename[i] ofType:@"jpg"]]];
        photo.caption = @"THIS IS AN IMAGE";
        [photos addObject:photo];
}

我有50个图像都有像“imagename1,imagename2”等名称。所以不要手动输入所有图像我只想循环它们但我不知道在ios中这样做的正确语法。

3 个答案:

答案 0 :(得分:5)

试试这个:

for (int i = 1; i <= 50; i++) {
    NSString *filename = [NSString stringWithFormat:@"imagename%d", i];
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    MWPhoto *photo = [MWPhoto photoWithImage:image];
    photo.caption = @"Hi";
    [photos addObject:photo];
}

不要把所有东西塞进一条线上。它很难阅读和调试。

答案 1 :(得分:3)

这将为您提供已排序的图像数组:

NSArray * imagePaths = [[[NSBundle mainBundle] pathsForResourcesOfType: @"jpg" inDirectory: nil] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
NSMutableArray * images = [NSMutableArray array];

for (NSString * imagePath in imagePaths) {
    if ([imagePath rangeOfString: @"imagename"].location != NSNotFound) {
        [images addObject: [UIImage imageNamed: [imagePath lastPathComponent]]];
    }
}

无需担心总数

答案 2 :(得分:2)

你去吧

int i;

 for (i = 0; i < 49; i++) 
{

 NSMutableString *tempImgStr = [NSMutableString stringWithFormat:@"imagename%d.png", i+1];
 UIImage *image = [UIImage imageNamed:tempImgStr]
 photo = [MWPhoto photoWithImage:image];
        photo.caption = @"THIS IS AN IMAGE";
        [photos addObject:photo];
}