Search code examples
ioscocoansuserdefaultsicloudkey-value

Local key-value storage other than NSUserDefaults


I have followed the Apple documentation on syncing preferences via iCloud - essentially, iterating over every key in the 'updated' user info and setting it in [NSUserDefaults standardDefaults].

But I have some other data I would like to persist in the same format but which should not be synced - just a small array of NSDictionaries.

Is there a way to store these in the same fashion but in a separate place? Or should I change my 'update form iCloud' method to explicitly exclude these by key name? That seems a little inflexible and error prone to me (remembering to update the 'keys to exclude' whenever I change what I want to store locally).


Solution

  • You can store such data in "<Library folder>/Application Support/<app bundle id>" - use the standard API to locate the user's Library folder (which will be in your container). The "Application Support" folder itself may not exist so you must check and create if needed. Your own app's folder won't exist unless you create it, so check and create.

    The various collection's have methods to read/write from URL's, e.g. for NSArray:

    + (id)arrayWithContentsOfURL:(NSURL *)aURL;
    - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag;
    

    Once you have the path to the directory above create a URL for an appropriately named file, e.g. "theArrayOfDictionaries.plist", and use these methods to read/write to it. The only caveat is the collection must only contain types that can be stored in a property list. If you have non-plist types, e.g. NSColor or your own classes, then you need to convert them to NSData before/after the write/read - see this page for how to do this for NSColor, other types can be handled similarly.

    HTH.