views:

70

answers:

2

I'm using a NSPersistantDocument backed by Core Data in my application.

Each document has a number of settings that are only relevant to that document. For example the document needs to hold the unique ID of an Address Book Group, to update it at a later date.

The way I'm thinking of approaching this is to have another model, DocumentSetting, which has two attributes; a key and a value, which hold NSString's.

Ideally I would like something similar to NSUserDefaults but stored within the document.

Has anyone done this before? Are there any better way to approach this?

+3  A: 

The setMetadata: method on NSPersistentStore can be used to store per-document settings. The docs for how to go about using the store's metadata can be found here. As advised in the docs though, there are some size limitations on what can be put in there. If you need to store something more substantial than a few key/value pairs, I would recommend making a new entity in your data model to store such data.

Brian Webster
A: 

As Brian says, the persistent store's metadata is a good place for this kind of thing. Alternatively, your idea to add a separate entity work as well (I've used both methods in the past). Keep in mind that if this DocumentSetting entity doesn't have relationships to other entities in your document model, you can put it into a separate xcdatamodel and merge the models at runtime using -[NSManagedObjectModel mergedModelFromBundles:]. At least this way you can keep your "source" model files isolated a bit.

In terms of strategy, unless you are going to have a very large number of these document settings or want to query them individually, you could use a transformable property and store an (archived) NSDictionary in your DocumentSettings entity. This would make the feel much more like the NSUserDefaults API which feels basically like a dictionary.

Barry Wark