swiftmacoscore-datanspersistentdocumentmanagedobjectcontext

Getting the managedObjectContext in a document-based app for preferences controller


I've got an OSX document-based app, written in Swift and would like to submit some data from my preferences window controller into my managedObjectContext.
Because the preferences window doesn't seem to be invoked through the NSPersistentDocument, but direct from the appDelegate, what's the best way to get hold of the managedObjectContext for that controller? Doing most of this using storyboards and bindings so far.
Am I right in thinking that if I instantiate a core-data stack in the application delegate, that negates the one supplied through the NSPersistentDocument (which would be defeating the purpose of the thing)?


Solution

  • What sort of data is this? Are these some sort of settings that are specific to the current document? I am curious only because there may be different solutions here depending on the particulars of what you want to accomplish.

    Edit: Usually preferences should be stored using NSUserDefaults, but assuming you do have a specific need to store this data in your persistent document, you should be able to use NSDocumentController to get a list of your persistent documents:

    let documents = NSDocumentController.sharedDocumentController().documents

    Or get just the current document. Either way you can get the managed object context from there:

    if let document = NSDocumentController.sharedDocumentController().currentDocument as? NSPersistentDocument { if let context = document.managedObjectContext { // do whatever is needed with the context } }