KCMutableDictionary is a subclass of
NSMutableDictionary that is transparently persisted in your app's keychain. The general idea is to make secure storage of small items in the keychain as easy as using a mutable dictionary.
Four restrictions are imposed:
KCMutableDictionarymay not be initialized with data. Use, for example,
Keys and values are restricted to property list objects, that is, objects that can be serialized with
NSPropertyListSerialization. This includes
NSNumber, but not (for example)
Mutable values may be stored in
KCMutableDictionary, but they will be replaced with immutable copies.
Reads are fast, but writes are (relatively) slow.
KCMutableDictionary.m to your project and
#import "KCMutableDictionary.h" as required. When the dictionary is instantiated (
[KCMutableDictionary dictionary] is as good a method as any), it automatically populates itself from the keychain. Stores are synchronous: the dictionary is immediately written to the keychain and then read back (so that the dictionary items are now immutable copies of the originals).
For security reasons, you may not want the dictionary to remain resident in memory once you're done with it. Do not remove items from the dictionary, since this will also remove them from the backing store in the keychain. Instead, release the dictionary by assigning
nil to its reference.
The serialized dictionary is stored by default in the keychain with the key
<bundleID>.__KCMutableDictionary__. Named dictionaries can be stored in the keychain as well; used the initializer
initWithName: to use a dictionary named
KCMutableDictionary was inspired by Mark Granoff's granoff/Lockbox and a suggestion by Ernesto Rivera. Matt Gallagher has a useful post on the subject of subclassing
NSMutableDictionary at Cocoa with Love that I didn't stumble on until too late to save me some time. Thanks also to my many smart friends.