iphone - 获取文件名到 NSArray

标签 iphone objective-c

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

例如:

一个.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/

相关文章:

objective-c - XCode 显示函数参数热键

iphone - MKMapView userLocation 在 iOS5 上错误但在 iOS4.2 上正确

iphone - 如何使用日期选择器在按钮上显示选定的日期?

iphone - AVMutableAudioMix 和 AVAssetExportSession

iphone - UIPickerView 如何显示未选择的内容?

iphone - 将 JSON 属性响应转换为 BOOL

ios - Restkit — 如何映射具有可变键名的 json 对象

iphone - 为表格 View 中的单元格设置可变高度

ios - 使用 iOS 7.1 从 UICollectionViewController 进行推送转换时 UINavigationBar 后面的深色背景

iphone - SQLite3 数据库未通过 NSLog 在控制台上显示条目(将数据保存到数据库有效)