2015-02-10 120 views
-1

我有幾個圖像在「ProjectImages」文件夾中,並希望從上述文件夾中檢索圖像文件名並將其存儲在數組中,然後我想提取這些圖像的擴展名文件並將其存儲在另一個陣列中。我能夠從文件夾中檢索圖像文件名並提取擴展名,但我不知道如何將提取的文件名存儲在另一個數組中。下面是代碼提取擴展名並保存圖像名稱

//get image name from the folder 
    NSError *error; 
    NSFileManager *fileMgr = [NSFileManager defaultManager]; 
    NSString *directory = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"ProjectImages"]; 

    NSArray *files=[fileMgr contentsOfDirectoryAtPath:directory error:&error]; 

//extract the extension 
NSString *imageNames=nil; 
    for (NSString *name in files) { 
     if (!imageNames) imageNames = [[name lastPathComponent] stringByDeletingPathExtension]; 
     else imageNames = [imageNames stringByAppendingFormat:@" %@",[[name lastPathComponent] stringByDeletingPathExtension]]; 

    } 
NSLog(@"%@",imageNames); --> This returns one single name with all the image name, which i don't want, instead i want to store each extracted file name in array and wanted to compare the string entered by the user with this array. how to do it ? 
+1

你不存儲任何數組中的任何。您正在構建一個空格分隔的文件名字符串。 – rmaddy 2015-02-10 20:01:51

回答

1
You are not storing image name in array 
Try this way 


    //get image name from the folder 
    NSError *error; 
    NSFileManager *fileMgr = [NSFileManager defaultManager]; 
    NSString *directory = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"ProjectImages"]; 
    NSArray *files=[fileMgr contentsOfDirectoryAtPath:directory error:&error]; 
    //extract the extension 
    NSMutableArray *array = [[NSMutableArray alloc]init]; 
    for (NSString *name in files) { 
     NSString imageName = [[name lastPathComponent] stringByDeletingPathExtension]; 
if ([array indexOfObject:imageName inRange:NSMakeRang(0,[array count])]!=NSNotFound){ 
//duplicate 
} 
else 
{ 
[array addObject:imageName]; 
} 

} 
    NSLog(@"%@",array); 
+0

謝謝shashi3456643!我用if([array containsObject:user_entered_string])來比較用戶輸入的字符串是否存在於可變陣列中,但它沒有給出任何結果。下面是代碼 (NSString * name in files){ NSString * imageName = [[last lastPathComponent] stringByDeletingPathExtension]; [imgaftext addObject:imageName]; if([imgaftext containsObject:message]){//消息是用戶輸入的字符串 NSLog(@「Yes」); } } – user3310076 2015-02-11 10:51:57

+0

你說你不要添加重複,如果已經存在,那麼不要添加你可以使用inRange。 – Shashi3456643 2015-02-11 12:12:21

+0

if([mutableArray indexOfObject:object inRange:NSMakeRang(0,[mutableArray count])]!= NSNotFound){// duplicate} – Shashi3456643 2015-02-11 12:16:33