2009-08-07 52 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