How to initialize a new instance of NSDocument in Swift?

Apple documentation suggests overriding the convenience initialization NSDocument (initWithType: error :), as described here .

However, since this is an init convenience, I cannot override it. But when creating a new document, I still need to execute some code. I do not want to execute this code when loading a document.

In my particular case, I am trying to initialize an NSPersistentDocument, but I doubt it is relevant.

What should I do?

+6
source share
2 answers

To execute the initialization 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 with Swift is that you cannot call the convenience initializer in super. Instead, you should delegate the designated initializer yourself. This means that you cannot take advantage of the superuser convenience initializers, and you must implement the initialization yourself, which means fileType = typeName above. As much as I like Swift, I find this nonsense: what's the point of reusing code that can be reused ??

+8
source

Work on the answer for Swift 1.

It needs to be modified to answer below in Swift 2:

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

The answer was given here: http://meandmark.com/blog/2015/07/nsdocument-initwithtype-in-swift-2/

Sent for convenience, as this is a common problem.

+10
source

Source: https://habr.com/ru/post/980267/


All Articles