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:
-
KCMutableDictionary
may not be initialized with data. Use, for example,+dictionary
or+dictionaryWithName:
. -
Keys and values are restricted to property list objects, that is, objects that can be serialized with
NSPropertyListSerialization
. This includesNSData
,NSString
,NSArray
,NSDictionary
,NSDate
, andNSNumber
, but not (for example)NSSet
. -
Mutable values may be stored in
KCMutableDictionary
, but they will be replaced with immutable copies. -
Reads are fast, but writes are (relatively) slow.
Copy KCMutableDictionary.h
and 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 any local reference and calling -forget
to release the singleton 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; use the convenience method +dictionaryWithName:
to use a dictionary named <bundleID>.__KCMutableDictionary__.<name>
. All dictionaries are singletons as of v1.2; multiple instantiations with the same name refer to the same object.
1.2: All dictionaries are singletons. The method -initWithName:
no longer exists; use +dictionaryWithName:
instead.
1.1: The default dictionary is a singleton.
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.