Search code examples
iosnsuserdefaultsicloud

Preventing NSUserDefaults from iCloud Backup


There are three ways to write persistently to the device in iOS that I'm aware of:

  1. NSUserDefaults
  2. Custom Objects - Archived and Written to a PATH in NSDocuments
  3. SQLite

Apple provide a mechanism to prevent iCloud backups with #2 i.e.

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL

I use NSUserDefaults to store three images but to adhere to iOS Data Storage Guidelines - How do I prevent Backups with iCloud with NSUserDefaults?

This question has been asked several times on SO but there is no clear comprehensive answer yet.

Is there a such a function or do I have to change storing images using method #2. I was hoping something convenient like:

- (BOOL)addSkipBackAttributeForStandardUserDefaultsKey:(NSString *)

exists.


Solution

  • There's no mechanism for this. NSUserDefaults is not intended to be used for saving app data. It's there to hold user preferences and other settings the app needs, but isn't intended as a full data persistence system.

    It's not accurate to say that this "...[Apple's] mechanism for storing data can't adhere to it's own guidelines" because that's not the purpose of this API. In this case specifically, if those images should not be backed up, then that's absolute evidence that user defaults is the wrong place to store them.

    You should save the images to files. If you have UIImage, this is simple. UIImage conforms to NSCoding, so it's easy to convert to/from an NSData. And NSData includes convenience methods to read/write objects to files. If the file names might change, you could reasonably put the file names in user defaults. If the file names are known in advance and can't change, then there's no reason to store them.