You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止MacOS SwiftUI文档类应用记住文档浏览器上次打开目录

问题根因

你之前修改applicationSupportsSecureRestorableState不生效,是因为该方法仅控制App全局窗口、布局状态的恢复,文档浏览器的最近访问目录是NSDocumentController独立维护的状态,不受全局恢复状态开关控制。

目录存储位置

该记录存储在App的用户偏好配置文件中,路径为:
~/Library/Preferences/[你的App Bundle ID].plist
对应的偏好键为NSNavLastRootDirectory,如果你的App支持多种自定义文档类型,还会生成带文档类型后缀的NSNavLastRootDirectory_<文档类型UTI>格式的键,分别存储不同类型文档的最近访问路径。

禁用自动恢复目录的两种方案

方案1:启动时清空历史记录

在AppDelegate的applicationWillFinishLaunching回调中直接删除对应的偏好值,从根源清除上次存储的目录记录:

func applicationWillFinishLaunching(_ notification: Notification) {
    // 清除通用最近目录
    UserDefaults.standard.removeObject(forKey: "NSNavLastRootDirectory")
    // 如有自定义文档类型,遍历删除对应后缀的键
    UserDefaults.standard.dictionaryRepresentation().keys.forEach { key in
        if key.hasPrefix("NSNavLastRootDirectory_") {
            UserDefaults.standard.removeObject(forKey: key)
        }
    }
}

方案2:自定义文档控制器强制指定默认目录

子类化NSDocumentController重写打开面板的调用逻辑,每次弹出文件选择器前强制覆盖目录路径,完全忽略历史记录:

  1. 实现自定义文档控制器
class CustomDocumentController: NSDocumentController {
    override func runModalOpenPanel(_ openPanel: NSOpenPanel, forTypes types: [String]?) -> Int {
        // 替换为你需要的默认目录,比如用户文稿目录
        openPanel.directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        return super.runModalOpenPanel(openPanel, forTypes: types)
    }
}
  1. 在App启动时注册自定义控制器
    在applicationWillFinishLaunching中初始化自定义单例,替换系统默认的文档控制器:
func applicationWillFinishLaunching(_ notification: Notification) {
    _ = CustomDocumentController.shared
}
SwiftUI DocumentGroup 适配说明

上述方案无需修改原有DocumentGroup的初始化代码,自定义NSDocumentController会自动接管DocumentGroup的文件选择逻辑,实现默认目录注入。

注意:如果你的App开启了沙盒,需要确保你指定的默认目录在App的沙盒权限允许访问的范围内,否则会自动回退到默认路径。

内容的提问来源于stack exchange,提问作者altimes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:24:02