做文件管理的时候,难免会用到搜索功能,搜索的方法有很多种,比如先对文件夹里的所有文件遍历后查找,而使用cocoa提供的利用spotlight来进行搜索,无疑是效率最高的一种。
下面介绍一下如何使用NSMetadataQuery来进行文件的检索。
一、首先,创建一个实例:
NSMetadataQuery *metadataQuery = [[NSMetadataQuery alloc] init];
设置一个监听函数来接受检索进度和结果:
NSNotificationCenter *nf = [NSNotificationCenter defaultCenter];
[nf addObserver:self selector:@selector(queryNote:) name:nil object:metadataQuery];
函数queryNote的定义如下:
- (void)queryNote:(NSNotification *)note {
// 查看 [note name], 可以获取事件类型
if ([[note name] isEqualToString:NSMetadataQueryDidStartGatheringNotification]) {
// 检索开始的消息
} else if ([[note name] isEqualToString:NSMetadataQueryDidFinishGatheringNotification]) {
// 检索完成的消息
} else if ([[note name] isEqualToString:NSMetadataQueryGatheringProgressNotification]) {
// 检索中...,会时时更新检索到的数据。NSMetadataQuery不会等把所有的数据检索完成才发数据,检索到一批后就会把数据更新,这就会减少检索时的等待。
} else if ([[note name] isEqualToString:NSMetadataQueryDidUpdateNotification]) {
// 当检索的文件目录范围内有文件操作时,比如新建、删除等操作时,会更新检索结果
}
}
检索结果会放倒NSMetadataQuery的实例属性里面,比如metadataQuery.resultCount存储文件数量,metadataQuery.results存储所有的文件,results里面存储的是NSMetadataItem对象,比如如果想获取检索到的文件路径,可以这样:
NSMetadataItem *item = [metadataQuery.results objectAtIndex:index];
NSString *filePath = [item valueForKey:(id)kMDItemPath];
想获取其它属性,可以参考kMDItemPath的相关定义。
二、如何开始检索
首先,设置检索类型,需要通过NSPredicate来完成。
比如,要检索图片,可以这样:
NSPredicate *predicateKind = [NSPredicate predicateWithFormat:@"kMDItemContentTypeTree == 'public.image'"];
如果检索时想要过滤掉一些查找,比如不去查找邮件信息,可以这样:
NSPredicate *emailExclusionPredicate = [NSPredicate predicateWithFormat:@"(kMDItemContentType != 'com.apple.mail.emlx') && (kMDItemContentType != 'public.vcard')"];
predicateKind = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:predicateKind, emailExclusionPredicate, nil]];
设置好NSPredicate后,把NSPredicate实例设置给metadataQuery:
[metadataQuery setPredicate:predicateKind];
设置检索目录:
[metadataQuery setSearchScopes:pathArray];
开始检索:
[metadataQuery startQuery];
如果想要停止检索:
[metadataQuery stopQuery];
三、优点和不足
优点就是检索速度快,效率高。
不足体现在,因为是利用spotlight进行检索,所以要依赖系统对每个文件所做的元数据索引,这也是速度快的原因。但是,一些文件Mac系统是不认识的,或是做的索引不对,我就遇到过一次,检索所有的压缩包,居然有rar格式等常用的压缩包没有检索出来,应该就是和系统对文件所做的索引有关。