我的图像文件夹中有图像,我想用文件名字符串初始化一个数组...
例如:
一个.png、两个.png、三个.png
我想将数组初始化为[“一”,“二”,“三”]
最佳答案
试试这个:
//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
对象的指针来获取有关问题的信息。
关于iphone - 获取文件名到 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1244265/