How to code NSDocuments data() function?

I need to see a sample code in order for me to understand. I am learning about NSDocuments, having created the starting template from Xcode. My Document consists of an Integer and the storyboard has a field to display and a button to increment the value. I need to learn how to store and read my Document data, a single Integer. This is what Xcode gives me:

var myData: Int = 0 //my Document's Data.

override func data(ofType typeName: String) throws -> Data {

throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)

}


override func read(from data: Data, ofType typeName: String) throws {

throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)

}


ive tied a few guesses but am completely lost; help me please.

Answered by OOPer in 416391022

A simple example for your simple data:

    override func data(ofType typeName: String) throws -> Data {
        return String(myData).data(using: .utf8) ?? Data()
    }

    override func read(from data: Data, ofType typeName: String) throws {
        self.myData = Int(String(data: data, encoding: .utf8) ?? "") ?? 0
    }

You create a Data which contains all the info of your Document in `data(ofType:)`,

And you retrieve all the info of your Document from the data in `read(from:ofType:)`.


In usual document-based app, a Document would not have multiple types and you can ignore typeName.

Accepted Answer

A simple example for your simple data:

    override func data(ofType typeName: String) throws -> Data {
        return String(myData).data(using: .utf8) ?? Data()
    }

    override func read(from data: Data, ofType typeName: String) throws {
        self.myData = Int(String(data: data, encoding: .utf8) ?? "") ?? 0
    }

You create a Data which contains all the info of your Document in `data(ofType:)`,

And you retrieve all the info of your Document from the data in `read(from:ofType:)`.


In usual document-based app, a Document would not have multiple types and you can ignore typeName.

Thank you for your response; I am grateful and learned something new today.

How to code NSDocuments data() function?
 
 
Q