Searching for files using NSMetadataQuery does simply nothing

↘锁芯ラ 提交于 2019-12-21 12:24:50

问题


I try to use NSMetadataQuery and NSPredicate to search for files. After several hours of trying and searching for solutions (I'm new to swift) I have a small example. It compiles fine but the results are zero. I tried different predicates but at the end metadataQuery.resultCount is always 0. Anyone has an idea whats going wrong?

class AppDelegate: NSObject, NSApplicationDelegate {
var metadataQuery: NSMetadataQuery!
var metadataQueryDidUpdateObserver: AnyObject?
var metadataQueryDidFinishGatheringObserver: AnyObject?


@IBOutlet weak var window: NSWindow!

func applicationDidFinishLaunching(aNotification: NSNotification) {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "initalGatherComplete:", name: NSMetadataQueryDidFinishGatheringNotification, object: nil)

    metadataQuery = NSMetadataQuery()
    metadataQuery.searchScopes = [NSMetadataQueryIndexedLocalComputerScope]
    metadataQuery.predicate = NSPredicate(format: "%K LIKE '*'", NSMetadataItemFSNameKey)
    metadataQuery.startQuery()

}

func initalGatherComplete(notification: NSNotification) {
    metadataQuery.stopQuery()

    let resultCounter = metadataQuery.resultCount
    NSLog("%lu", resultCounter)

    NSNotificationCenter.defaultCenter().removeObserver(self, name: NSMetadataQueryDidFinishGatheringNotification, object: nil)
}

And last but not least: the current predicate should list all files, but at the end the predicate should only list applications. whats the best practice to create such a predicate? I planned to filter for the extension .app but perhaps there is a better way?

Thanks!


回答1:


Check your predicate syntax. The LIKE operator isn't available for NSMetadataQuery predicate searches (in fact NSPredicate uses a quite similar but actually different set of operators and behavior in the context of Spotlight metadata searches.)

NSMetadataQuery's syntax for glob searches just uses an equals sign:

NSPredicate(format: "%K ==[cd] '*'", NSMetadataItemFSNameKey)


来源:https://stackoverflow.com/questions/28263182/searching-for-files-using-nsmetadataquery-does-simply-nothing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!