0

What I'm trying to do is store some data from a MacOS App with NSDocument provided class in a file. I decided to use SwiftUI , but all tutorials I found are using Storyboards. And from those I cannot adapt how to get the data from my textfield into my NSDocument class. As far as I got it I need to init my variables in the NSDocument class like this

class Document: NSDocument {

@objc dynamic var contents = "Foo"

public init(contentString: String) {
    self.contents = contentString
    }
/* ... */
}

and in the same class I can save this string using

override func data(ofType typeName: String) throws -> Data {
    return contents.data(using: .utf8) ?? Data()
    
    throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}

So in my view generated with SwiftUI I can access this using

struct MainTableView: View {

@State var doc = Document.init()

var body: some View {
    TextField("My text", text: self.$doc.contents)
    }
}

But - as I'm using only an instance it always saves "Foo" - no matter what I type into my TextField.

Besides - another question that will follow up right away: On the long run I don't want to store a string only. I'll have 3 different 2D-Arrays with different data-structures. Is NSDocument able to handle this by itself or do I need to convert those to JSON/XML/...-String and store this as a file?

  • Have you read the title of your topic? – El Tomato Jul 15 '20 at 08:16
  • Edited to make my question more clear. – JacquesNorris Jul 15 '20 at 08:44
  • I have not used SwiftUI yet, so no clue about the first question. But NSDocument is an abstract class and you have to provide all the routines for reading and writing. You should probably use NSPersistentDocument, as it does that for you. It is much easier to use. – Dirk Aug 10 '20 at 08:06
  • In the meantime I discovered the opportunity to use Core Data in a Document based app. Makes a lot of things easier - probably as @Dirk suggested by using NSPersistentDocument instead of NSDocument. Also this kinda solved my problem, as I just pass in the managedObjectContext and am happy with that. It's not actually the solution to my question, but my problem is solved for now. – JacquesNorris Aug 17 '20 at 08:05

0 Answers0