How to use Core Data with iCloud

Using Core Data with iCloud seems to be one of the best kept secrets Apple have to offer. For something so relatively simple it’s a surprising brain teaser if you try to follow the scraps of documentation you find.

Let’s take a “human look” at how this works. First we’ll examine the principle, followed by code samples that actually work. It’s less complicated than it seems, so hang in there.

This approach is working fine in iOS 7.1 and 6.1. However it no longer works since iOS 8.

iCloud Core Data in Principle

Testing

To test this, deploy the app on two devices. Initial deployment may take some time, especially on iOS 6 depending on the store size. On iOS 7 the store is setup asynchronously and will return faster – but I can’t overemphasise this enough: Have Patience, Young Skywalker!

When both devices are up and running, add records to either device, then wait for them to show up on the other device. You can also delete and change them. It’s a lot of fun to watch!

Note that since Xcode 5 you can use the Simulator for testing too: just make sure you’re logged into the same iCloud account as your device. Simulator will take much longer to read changes, iDevices take between 10 and 30 seconds to show new results.

Working Project on GitHub

You can get the source code for this exercise on GitHub. Make sure you replace the Bundle ID (in Xcode) and Team ID (in grabCloudURL) with your own values for this to work:

Post navigation

2 thoughts on “How to use Core Data with iCloud”

Note on iOS 6 and the Simulator

The iOS Simulator only understands iCloud related things as of iOS 7. Therefore, trying to run the above on the iOS 6 Simulator will end with an exception because the URL for the iCloud folder will be nil.

It will work fine on a real device though – just thought I’d mention it.