Get NSDocument from NSObject

64 Views Asked by At

i am on macOS, objective-c, not iOS. I am currently re-writing my app to be document based. I now save the reuired data in each NSDocument file as property which works great including autosave.

I can access that data from NSViewControllers by

self.view.window.document.mydata

I also can access the data by

[[NSDocumentController sharedDocumentController] currentDocument].mydata

But as documentation says to the method above

The value of this property is nil if it is called when the app is not active.

My issue is that i have (tons of) custom NSObjects in a document that handle stuff and need access to that data. This also happens in the background (with timers). What is the best way to reach the document from a NSObject if the app is in the background and no window is available?

Would i need to pass the document to each object on creation? This does not feel correct.

1

There are 1 best solutions below

0
skaak On

(Based on comments) Here is an example. Albeit for iOS. The document itself is made up of a large number of interconnected objects stored across a number of files. Inside UIDocument when the document data is stored I create a summary and store that in a separate file (inside the document) called sum.

Elsewhere I need to present some info on the document but I do not need to restore the whole document or get all the objects up and linked and running. I just need to read from the summary file. This is in fact the second iteration, earlier I did restore it all but simplified it a lot by creating this summary whenever the document is saved.

That said, maybe you could do with such a summary where you store essential stuff you need when accessing the document data outside of NSDocument?

Anyhow, here is that bit of code.

NSDictionary < NSString *, NSFileWrapper * > * fDic = self.wrapper.fileWrappers;
NSFileWrapper * sumWrapper = [fDic objectForKey:@"sum"];

This is very similar to what is happening inside the UIDocument file loading and saving hooks and would be similar to the same for NSDocument.

Anyhow, once I have the sumWrapper I can extract what I need from there without having to restore the full document. But even if I needed the full document I could just restore all of the file wrappers in the dictionary and use them just as in the document.

I hope this helps. A document can contain anything. In my case it is fairly granular and spread across a lot of files which makes it easy to access just bits of the document. If you store all of your objects into a single file then it will be a lot more difficult unless you move all of that functionality into a separate support class that you can then use both inside and outside of NSDocument.