How do I initialise a new NSDocument instance in Swift?

岁酱吖の 提交于 2019-12-05 23:05:02

问题


Apple documentation suggests to override an NSDocument convenience init (initWithType:error:) as described here.

However, as this is a convenience init, I cannot override it. But I still need to execute some code when a new document is created. I do not want to execute that code when I load a document.

In my particular case I try to initialise an NSPersistentDocument, but I doubt that is relevant.

What shall I do?


回答1:


To execute init code for a new document:

// 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
}

The problem in Swift is that you can not call a convenience initializer in super. Instead you must delegate to a designated initializer in self. This means that you can't take advantage of any of supers convenience initializers and you must implement the initialization your self---hence fileType = typeName above. As much as I like Swift, I find this stupid: what's the point of re-implementing code that could be reused!?




回答2:


Above answer works for Swift 1.

It has to be changed to answer below in Swift 2:

convenience init(type typeName: String) throws {
    self.init()
    // Rest of initialization code here
}

This was answered here: http://meandmark.com/blog/2015/07/nsdocument-initwithtype-in-swift-2/

Reposted for convenience since this is a common problem.



来源:https://stackoverflow.com/questions/27694877/how-do-i-initialise-a-new-nsdocument-instance-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!