2014-01-23 125 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

是真的,我個人喜歡可變字符串。只是我的事情:-) –