Does the AppKit framework provide a way to store NSUserDefaults
per NSDocument
? If not, how would you recommend to implement this?

- 119,096
- 131
- 338
- 476
2 Answers
Use an NSDictionary
. Store its contents along with the document. If the format you're saving into can't be modified to contain this dictionary, you might be able to switch to "document bundles", also called "document packages" -- directories containing both the data and a plist with the contents of the dictionary.
If you want to explicitly want to store per-document data inside the [NSUserDefaults standardUserDefaults]
-provided facility, you may want to look into organizing things like this:
- documentSpecificSettings - NSArray
- item 0 - NSDictionary
- url - NSData containing NSURL's bookmark
- some_key - your custom key
- another_key - your custom key
- item 1 - NSDictionary
- url - NSData containing NSURL's bookmark
- some_key - your custom key
- item 0 - NSDictionary
See documentation for NSURL
, specifically +bookmarkDataWithContentsOfURL:error:
and +URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:
. There are more methods around, but these are the ones you'll want to use.
As far as I understand it, you'll have to manually track whether or not the document still exists when resolving the bookmark into the URL. And I suspect you'll have to resolve each URL in the dictionary to see if it applies to your document.
This appears more complex than simply storing a dictionary along with the document.

- 9,529
- 9
- 60
- 111
If you have some key that identifies the document you can store an object (dictionary...) with that key in NSUserDefaults
. Or, depending on how you define a "document" it could contain its own meta-data.

- 30,888
- 4
- 42
- 57
-
With the first approach, is there a way to avoid keeping the document-specific defaults if the document is deleted? – hpique Nov 15 '12 at 14:25
-
Nothing automatic comes to mind. You'd probably have to run a sanity check on the document-related settings to verify that the documents they referenced were still valid. – Phillip Mills Nov 15 '12 at 14:33