利用NSMetadataQuery進行本地文件檢索使用總結

做文件管理的時候,難免會用到搜索功能,搜索的方法有很多種,比如先對文件夾裏的所有文件遍歷後查找,而使用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格式等常用的壓縮包沒有檢索出來,應該就是和系統對文件所做的索引有關。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章