我正在尝试获取用户 iCloud 文件夹中的目录列表。我研究了如何查找特殊类型的文件(例如 txt 文件),它工作正常:
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
_query = query;
//Search all files in the Documents directories of the application’s iCloud container directories:
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K ENDSWITH '.txt'", NSMetadataItemFSNameKey];
[query setPredicate:pred];
[query startQuery];
但是,我现在试图只获取目录。我已经阅读了有关NSPredicate的文档,但我不知道如何去寻找目录。我猜 NSPredicate 不是为此而生的?我可以检查是否有这样的目录:
BOOL isDir;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDir];
if (exists) {
/* file exists */
if (isDir) {
/* file is a directory */
}
}
但是如何将此应用于 NSMetadataQuery,我不知道。如果我能得到任何帮助,我将不胜感激。
编辑:
我将谓词更改为[NSPredicate predicateWithFormat:@"%K.pathExtension = ''", NSMetadataItemFSNameKey];
然后我确定查询何时完成,如下所示:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates]; // You should invoke this method before iterating over query results that could change due to live updates.
[query stopQuery]; // You would call this function to stop a query that is generating too many results to be useful but still want to access the available results.
[self loadData:query];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:query];
_query = nil; // we're done with it
}
最后,我进行了计数,但是无论我在云中拥有多少目录,这总是会给我 0(我通过 Lion 和 Mobile Documents 文件夹检查了这一点;例如,我有 Documents/myTXTs 等)。这很奇怪。如果我对文本文件进行计数,它会给我 4,因为我有 4 个 txt 文件。所以我猜我的目录没有被计算在内:
- (void)loadData:(NSMetadataQuery *)query {
NSLog(@"Query count %i", [query resultCount]);
...