苹果文档建议重写一个NSDocument便利的init(initWithType:描述错误:) 这里.
但是,由于这是一个方便的初始化,我无法覆盖它.但是我仍然需要在创建新文档时执行一些代码.我加载文档时不想执行该代码.
在我的特定情况下,我尝试初始化NSPersistentDocument,但我怀疑这是否相关.
我该怎么办?
小智 10
以上答案适用于Swift 1.
必须在Swift 2中将其更改为以下答案:
convenience init(type typeName: String) throws {
self.init()
// Rest of initialization code here
}
Run Code Online (Sandbox Code Playgroud)
这在这里得到了解答:http://meandmark.com/blog/2015/07/nsdocument-initwithtype-in-swift-2/
为方便起见,因为这是一个常见问题.
要为新文档执行init代码:
// Create new document (only called for new documents)
convenience init?(type typeName: String, error outError: NSErrorPointer) {
self.init()
fileType = typeName
// add your own initialisation for new document here
}
Run Code Online (Sandbox Code Playgroud)
Swift中的问题是你不能在super中调用一个方便的初始化器.相反,您必须委托自己指定的初始化程序.这意味着你不能利用任何超级便利初始化器,你必须实现自己的初始化 - 因此fileType = typeName在上面.尽管我喜欢Swift,但我觉得这很愚蠢:重新实现可以重用的代码是什么意思!?
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |