Search code examples
swiftnsdocument

How do I initialise a new NSDocument instance in Swift?


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?


Solution

  • 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.