有没有办法告诉-[NSFileManager contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:]
方法在收集目录内容时排除目录名?
我有一个显示文件夹的树视图,并且想要在表视图中显示唯一的文件,但我似乎无法找到一个键或任何其他方式来排除文件夹。我想我可以迭代返回的数组,只将文件填充到第二个数组中,这个数组将用作数据源,但这种双重处理似乎有点狡猾。
如果nil
是一个目录,我也尝试从tableView:viewForTableColumn:row:
方法返回NSURL
,但这只会在表格中产生一个空白行,所以这也不好。< / p>
当然有一种方法可以告诉NSFileManager
我只想要文件吗?
答案 0 :(得分:15)
您可以更深入地了解目录枚举器。
这个怎么样?
NSDirectoryEnumerator *dirEnumerator = [localFileManager enumeratorAtURL:directoryToScan includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:nil];
NSMutableArray *theArray=[NSMutableArray array];
for (NSURL *theURL in dirEnumerator) {
// Retrieve the file name. From NSURLNameKey, cached during the enumeration.
NSString *fileName;
[theURL getResourceValue:&fileName forKey:NSURLNameKey error:NULL];
// Retrieve whether a directory. From NSURLIsDirectoryKey, also
// cached during the enumeration.
NSNumber *isDirectory;
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if([isDirectory boolValue] == NO)
{
[theArray addObject: fileName];
}
}
// theArray at this point contains all the filenames
答案 1 :(得分:11)
最好的选择是使用enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:
填充排除文件夹的数组。
NSFileManager *fm = [[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:directoryToScan
includingPropertiesForKeys:@[ NSURLNameKey, NSURLIsDirectoryKey ]
options:NSDirectoryEnumerationSkipsHiddenFiles | NSDirectoryEnumerationSkipsSubdirectoryDescendants
errorHandler:nil];
NSMutableArray *fileList = [NSMutableArray array];
for (NSURL *theURL in dirEnumerator) {
NSNumber *isDirectory;
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if (![isDirectory boolValue]) {
[fileList addObject:theURL];
}
}
这将为您提供一组表示文件的NSURL
个对象。
答案 2 :(得分:3)
没有办法获取内容,包括目录,然后从那里削减它们,但这不是一个真正的问题。
您从文件管理器获取的NSURL
将告诉您每个文件系统对象是否都是一个目录,只要您在“属性为密钥”列表中包含NSURLIsDirectoryKey
项目
有许多方法可以在获得数据后使用该信息过滤数组 - 或者通过枚举,正如其他答案所示。
您可以向NSURL
添加访问者方法:
@implementation NSURL (RWIsDirectory)
- (BOOL)RWIsDirectory
{
NSNumber * isDir;
[self getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:NULL];
return [isDir boolValue];
}
@end
然后使用谓词:
[directoryContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"RWIsDirectory == NO"]];