我目前正在构建一个 mac 应用程序,将来应该能够在 OS X 上杀死和启动应用程序。
为此,我需要找到一种方法来获取机器上所有已安装应用程序的列表。
我已经做了很多研究,并决定使用 Spotlight 和 NSMetadataQuery 来获取列表。
我能够找到关于上述主题的这篇文章,并开始在 Swift 2.2(该项目的首选武器)中实现该功能。通过一些翻译,我能够使其工作,代码现在成功构建并运行。但是,在运行时,我似乎遇到了查询本身的问题:
<NSMetadataQuery: 0x6080000e3880> is being deallocated without first calling -stopQuery. To avoid race conditions, you should first invoke -stopQuery on the run loop on which -startQuery was called
这是我目前正在使用的代码。
public func doSpotlightQuery() {
query = NSMetadataQuery()
let predicate = NSPredicate(format: "kMDItemKind ==[c] %@", "Application")
let defaultNotificationCenter = NSNotificationCenter()
defaultNotificationCenter.addObserver(self, selector: #selector(queryDidFinish(_:)), name: NSMetadataQueryDidFinishGatheringNotification, object: nil)
query.predicate = predicate
query.startQuery()
}
public func queryDidFinish(notification: NSNotification) {
for i in 0 ... query.resultCount {
print(query.resultAtIndex(i).valueForAttribute(kMDItemDisplayName as String))
}
}
测试
mdfind "kMDItemKind == 'Application'"
我的mac终端中的命令(各种变体)也没有给我任何结果,这让我想到了我的问题:
我是否以错误的方式设置了查询,或者此命令在“El Capitan”中不起作用?
有人可以帮我找出我的错误吗?我肯定很想最终完成这项工作!