I have a fairly simple document app with a tableView... using MVVM... can't figure out how to get my data to the Document class so that it can be saved / loaded. I'm not listing the Document class here because it's the exact boilerplate that comes with a document app. As you can see right now my data is saved in the ViewModel... the array called "notes." That's what I want to save... perhaps by using JSON or maybe NSKeyedArchiver, not sure what's best. I just don't know how to have access from the Document class to the notes array. I've looked a little at representedObject but it's so confusing... any help would be much appreciated.
Model:
View Model:
View Controller:
Model:
Code Block import Foundation struct Note: Codable { var timecodeIn: String var timecodeOut: String var note: String var comment: String init(timecodeIn: String, timecodeOut: String, note: String, comment: String) { self.timecodeIn = timecodeIn self.timecodeOut = timecodeOut self.note = note self.comment = comment } }
View Model:
Code Block import Foundation class ViewModel: NSObject, Codable { // MARK: - Properties var notes = [Note]() //this ultimately is the array I want saved. Maybe it doesn't go here? // MARK: - Init override init() { super.init() } // MARK: - Public Methods //set note func setNote(note: Note) -> Void { notes.append(note) } //delete 1 note func deleteNote(atIndex index: Int) { notes.remove(at: index) } //delete <1 notes func deleteNotes(atIndexSet set: IndexSet) { var count = 0 for index in set { notes.remove(at: (index - count)) count += 1 //funky, but it works! } } }
View Controller:
Code Block import Cocoa class ViewController: NSViewController { // MARK: - IBOutlet Properties ... // MARK: - Properties var viewModel = ViewModel() // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } override var representedObject: Any? { didSet { } } override func viewWillAppear() { super.viewWillAppear() tableView.reloadData() } // MARK: - IBAction Methods @IBAction func addNote(_ sender: NSButton) { ... viewModel.setNote(note: tempNote) tableView.reloadData() } @IBAction func removeNote(_ sender: NSButton) { ... viewModel.deleteNotes(atIndexSet: tableView.selectedRowIndexes) } } // MARK: - ViewController extensions extension ViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return viewModel.notes.count } } extension ViewController: NSTableViewDelegate { ... }