获取NSArray的文件名

use*_*736 2 iphone objective-c

我在Images文件夹中有图像,我想初始化一个包含文件名字符串的数组...

例如:

one.png,two.png,three.png

我想将我的数组初始化为["one","two","three"]

Ale*_*ski 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];
}
Run Code Online (Sandbox Code Playgroud)

代码的第一部分检索给定目录中的文件名,并将它们添加到imagePaths数组中.

然后代码的第二部分循环遍历数组中的图像路径,并从末尾删除扩展(使用该stringByDeletingPathExtension方法),将它们附加到imageNames数组,该数组将包含给定目录中的所有文件,没有任何文件扩展名.

正如Graham Lee在他的代码中所做的那样NSError,如果出现错误,您可以提供指向对象的指针以获取有关问题的信息.