2009-08-07 51 views
2

我在圖片文件夾中的圖像,我想初始化文件名​​的字符串數組...獲取文件名的NSArray

例如:

one.png,two.png,三png格式

我想我的初始化數組[ 「一」, 「二」, 「三」]

回答

8

試試這個:

//Retrieve an array of paths in the given directory 
NSArray *imagePaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: @"/Images/" error: NULL]; 

if(imagePaths==nil || [imagePaths count]==0) { 
    //Path either does not exist or does not contain any files 
    return; 
} 

NSEnumerator *enumerator = [imagePaths objectEnumerator]; 
id imagePath; 
NSString *newImageName; 

NSMutableArray *imageNames = [[NSMutableArray alloc] init]; 

while (imagePath = [enumerator nextObject]) { 
    //Remove the file extension 
    newImageName = [imagePath stringByDeletingPathExtension]; 
    [imageNames addObject:newImageName]; 
} 

代碼的第一部分檢索給定目錄中文件的名稱,並將它們添加到imagePaths陣列中。

代碼的第二部分則循環通過陣列中的圖像路徑和從端部(使用stringByDeletingPathExtension方法)去除擴展,將它們附加到imageNames陣列,其中將包含在給定目錄中的所有文件沒有任何文件擴展名。

由於Graham Lee已在他的代碼中完成,因此您可以提供一個指向NSError對象的指針,以便在出現錯誤時獲取有關該問題的信息。

+0

在我有限的經驗中,這比追蹤.plist好一百萬倍。 – buildsucceeded 2011-10-11 20:14:57

4
NSError *error = nil; 
NSArray *imageFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: @"/path/to/Images/" error: &error]; 
if (imageFiles == nil) //handle the error