2014-01-23 126 views
3

我试图通过文件名来循环遍历文件名,这些文件名在结尾处都有一个相同的名称和增加的数字。我有这样的事情作为现在:通过文件名迭代

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中不知道正确的语法。

+0

在哪里你的文件吗?是在应用程序的根目录还是在应用程序数据中? –

+0

由于您正在从应用程序包中加载文件,因此您可能会更好,将所需的所有图像放入包中的子文件夹中,然后只需加载该目录中的所有图像即可。无需担心这些名字或他们的号码。 – Abizern

回答

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

不要硬塞到一切一行。这很难阅读和调试。

+0

打我吧.. –

+0

其实刚刚想出了与你发布的相同的解决方案:p谢谢你。 –

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

在这里你去

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

不需要使字符串可变。 – rmaddy

+0

是真的,我个人喜欢可变字符串。只是我的事情:-) –