iOS开发:如何从NSURL数组提取文件名并在UITableView中展示
解决提取CSV文件名并在UITableView展示的问题
看了你的代码,发现两个核心问题导致你没法正确获取每个CSV文件的文件名,而且排序逻辑的位置也不对,我来帮你修正:
问题分析
- 文件名提取错误:你现在用的是
documentDirectoryURL.lastPathComponent.stringByDeletingPathExtension,这拿到的是Documents目录的名称,而不是每个CSV文件的名字,完全搞错了操作对象。 - 排序逻辑位置错误:你现在是对所有文件数组
files排序,但之后才筛选出CSV文件,导致最终展示的csvFiltered数组并没有被排序,排序等于白做。 - 筛选条件小问题:
pathExtension返回的是不带.的后缀,原代码里写pathExtension='.csv'会导致筛选失效,匹配不到任何文件。
修正后的完整代码
NSError *err; NSFileManager *fileManager = [NSFileManager defaultManager]; NSURL *documentDirectoryURL = [fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:&err]; // 获取目录下所有文件(附带创建日期属性) NSArray *files = [fileManager contentsOfDirectoryAtURL:documentDirectoryURL includingPropertiesForKeys:@[NSURLCreationDateKey] options:0 error:&err]; // 筛选CSV文件(注意pathExtension不带点) NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension == 'csv'"]; NSMutableArray *csvFiltered = [[files filteredArrayUsingPredicate:predicate] mutableCopy]; // 按创建日期排序(支持切换升序/降序) BOOL ascending = YES; [csvFiltered sortUsingComparator:^(NSURL *lURL, NSURL *rURL) { NSDate *lDate, *rDate; [lURL getResourceValue:&lDate forKey:NSURLCreationDateKey error:nil]; [rURL getResourceValue:&rDate forKey:NSURLCreationDateKey error:nil]; // 处理文件获取不到创建日期的情况,避免崩溃 if (!lDate) return ascending ? NSOrderedAscending : NSOrderedDescending; if (!rDate) return ascending ? NSOrderedDescending : NSOrderedAscending; return ascending ? [lDate compare:rDate] : [rDate compare:lDate]; }]; // 提取每个CSV文件的文件名(带扩展名,若要去掉可追加.stringByDeletingPathExtension) NSMutableArray *allItems = [NSMutableArray new]; for (NSURL *paramURL in csvFiltered) { NSString *fileName = paramURL.lastPathComponent; // 如果需要不带.csv的文件名,替换成下面这行: // NSString *fileName = paramURL.lastPathComponent.stringByDeletingPathExtension; [allItems addObject:fileName]; } NSLog(@"%@", allItems); self.dirList = [allItems mutableCopy]; [self.data reloadData];
关键修正点说明
- 文件名提取:改用
paramURL.lastPathComponent,直接拿到当前URL对应的文件名(比如test.csv),如果需要去掉扩展名,就调用stringByDeletingPathExtension得到test。 - 筛选条件修正:把
.csv改成csv,因为pathExtension返回的后缀本身不带点,原条件会匹配不到任何文件。 - 排序逻辑调整:把排序操作移到筛选之后,对
csvFiltered数组排序,这样最终展示的文件是按创建日期排序好的。 - 空日期防护:增加了日期为nil的判断,避免因为某些文件获取不到创建日期导致崩溃。
UITableView数据源方法补充
确保你的UITableView数据源方法正确使用self.dirList:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dirList.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; cell.textLabel.text = self.dirList[indexPath.row]; return cell; }
内容的提问来源于stack exchange,提问作者pentaaax
相关产品推荐
相关产品推荐

