macOS下遍历已安装应用的更高效实现方法咨询
高效获取macOS已安装应用列表的方法
最优方案:使用Launch Services框架
macOS的Launch Services是系统级应用管理框架,它维护着所有已注册应用的数据库,直接查询该数据库的效率远高于遍历磁盘文件夹,和Launchpad、「打开方式」列表采用的是同一套底层机制。
实现代码
首先引入CoreServices框架,通过LSApplicationWorkspace获取标准化的应用信息:
import CoreServices import AppKit func getInstalledApplications() -> [(displayName: String, bundleURL: URL)] { let workspace = LSApplicationWorkspace.default() guard let appProxies = workspace.allApplications() as? [LSApplicationProxy] else { return [] } return appProxies.compactMap { proxy in // 过滤无效应用与系统预装应用(可根据需求调整筛选规则) guard let bundleURL = proxy.bundleURL, let displayName = proxy.localizedName, !bundleURL.path.hasPrefix("/System/Applications") else { return nil } return (displayName: displayName, bundleURL: bundleURL) }.sorted { $0.displayName < $1.displayName } // 按应用名称排序 }
在SwiftUI中集成列表
调用上述函数生成应用列表,点击直接打开对应应用:
ForEach(getInstalledApplications(), id: \.bundleURL) { app in AppBarMenuItem(itemAppName: app.displayName) .onTapGesture { NSWorkspace.shared.open(app.bundleURL) } }
原方案性能问题根源
你之前的遍历方法性能极差的核心原因:
FileManager.enumerator(atPath:)会递归遍历/Applications下的所有子目录,包括每个.app包内部的全部文件(比如Contents/Resources、Frameworks等),产生大量无意义的磁盘IO操作- 筛选条件
!element.contains("Contents")仅能排除部分路径,无法阻止枚举整个.app包的内部结构,导致CPU与磁盘占用持续高位,启动耗时被大幅拉长
内容的提问来源于stack exchange,提问作者Bunabyte
相关产品推荐
相关产品推荐

