iOS Code: MKiCloudSync – Sync your NSUserDefaults to iCloud with a single line of code
Just wrote this class, MKiCloudSync (100 lines of code) that auto syncs your NSUserDefaults to iCloud.
How to use?
All you need to do is to enable iCloud key value store entitlements, copy the files and forget about the rest.
Enable iCloud entitlements for your app. This is easily done in Xcode 4.2.1 by opening your target settings and checking “Enable Entitlements” from the summary tab.
This is illustrated below.
Enabling iCloud Entitlements in Xcode 4.2.1
If you are sharing settings with other apps, ensure that your iCloud Key-Value Store is the same across all those apps.
Drag the two files
into your project. You can find these files in the Source Code section of this post.
In your applicationDidFinishLaunchingWithOptions: method,
start the sync by calling,
You also have to #include the header file.
This is probably the only line of code you have to write!
There is no step 4. Continue using NSUserDefaults to save your settings. The MKiCloudSync class automatically syncs your settings to iCloud and restores them back to your NSUserDefaults when they are changed on other devices.
To top them all, it also posts a notification,
to let you know that a sync has been performed. You can listen to this notification and update your user interface from NSUserDefaults.
- Upgrading your existing iOS 4 apps to sync settings to iCloud is now super easy.
- With this class, you no longer have to add calls to NSUbiquitousKeyValueStore throughout your app. You can continue your existing method of saving them to NSUserDefaults. Everything is automatic. If your settings might change often, you can observe the notification kMKiCloudSyncNotification and update your user interface.
Royalty free for commercial or non-commercial use, though attribution will please me to write more such code