图片来自网络
在Xcode中创建Cocoa Application 工程时,通常有两种选择类型:<code>基于文档的Application</code> 和<code>非文档的Application</code>,具体是哪一种类型,关键在于创建工程的时候,你是否选中下图中的<code>Create Document-based Application</code>选项:
创建工程界面
基于文档的应用与非文档应用的主要区别:
然而 如果你在产品开发初期,创建的项目工程并没有选择<code>Create Document-based Application</code>选项,也就是说,你的项目是<code>非基于文档的Application</code>,但由于某种原因<code>(请不要问我是什么原因)</code>需要在后期的版本中添加<code>文档编辑</code>的功能,难道还要把整个项目重建一遍?!<code>场面不敢想象</code>,好了,<code>其实是有方法可以实现的</code>,请继续看下去。。。。
添加继承NSDocument的类文件
override func makeWindowControllers() {
// 获取Main.storyboard
let storyboard = NSStoryboard(name: "Main", bundle: nil)
// 获取window控制器
let controller = storyboard.instantiateController(withIdentifier: "NormalWindowsController") as! NSWindowController
// 添加窗口控制器到文档(产生关联)
self.addWindowController(controller)
// 获取内容控制器(通常是与用户交互的视图控制器)
editController = controller.contentViewController as! ViewController
// 对编辑控件进行初始化赋值
editController.editTextView.string = readText
}
// 保存文件时,系统会调用此方法进行数据存储
override func data(ofType typeName: String) throws -> Data {
let text = editController.editTextView.string ?? ""
return text.data(using: .utf8)!
}
// 打开文件时,系统会调用此方法进行数据读取
override func read(from data: Data, ofType typeName: String) throws {
readText = String(data: data, encoding: .utf8) ?? ""
}
// 是否需要自动保存编辑内容
override class func autosavesInPlace() -> Bool {
return true
}
添加Document Type
设置细节说明:
设置细节
取消initial Controller
Tip-for-day中的NormalApplication 文件夹
文中<code>错误难免</code>,欢迎各位在<code>评论中</code>指正,<code>绝不删帖</code>,这样便于<code>后面阅读的人</code>可以看到,并获得<code>正确的指引。</code>