Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 46 ยท Data, Networking and Persistence

Core Data, CloudKit and Sync

Know when Core Data still matters, how NSPersistentCloudKitContainer mirrors data to iCloud, what the key-value store is for, and how to design for sync conflicts.

SwiftData is the friendly front door to local storage, but it did not appear out of nowhere. Underneath, Apple's persistence story has long been Core Data, and it is still a working, widely used framework that you will meet in real projects. In this lesson you will learn what Core Data is, when you still reach for it, and how Apple's iCloud tools sync data between a user's devices.

Sync is where the hard problems live. Two phones can edit the same record while offline, and later both claim to be right. We cannot run CloudKit on this site, so the framework code below is read-only. The runnable examples are plain Swift simulations of the problems sync must solve: conflicting edits and deletes. If you have not yet seen the local side, read SwiftData Basics first.

Core Data in one page

Core Data is an object graph and persistence framework. You describe your entities (types, attributes, relationships) in a model file, normally .xcdatamodeld, and Core Data stores instances in SQLite by default. The main pieces map directly onto SwiftData ideas:

Core Data SwiftData equivalent
NSManagedObjectModel (the .xcdatamodeld file) Schema and @Model classes
NSPersistentContainer ModelContainer
NSManagedObjectContext ModelContext
NSFetchRequest and NSPredicate FetchDescriptor and #Predicate
@FetchRequest in SwiftUI @Query
Swift
import CoreData

final class PersistenceController {
    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "NotesModel")
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores { _, error in
            if let error { fatalError("Store failed to load: \(error)") }
        }
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

In SwiftUI you would inject container.viewContext into the environment and read data with @FetchRequest. That is a read-only sketch of the usual setup.

When Core Data still matters

For a new app that targets iOS 17 or later and has ordinary needs, SwiftData is the sensible default. Core Data is still the right choice, or the only choice, when:

  • Your app supports iOS 16 or earlier. SwiftData does not exist there.
  • You already have a Core Data app. Rewriting a stable data layer rarely pays off. The two can also work on the same store in some setups, so a gradual move is possible.
  • You need features SwiftData does not expose well, such as fine-grained batch operations (NSBatchInsertRequest, NSBatchDeleteRequest), NSFetchedResultsController for UIKit table views, persistent history tracking you inspect yourself, or sharing records with other iCloud users.
  • You need precise control over contexts, merge policies and performance on very large data sets.

None of that is a reason to avoid SwiftData. It is a reason not to be surprised when a job posting or a legacy codebase asks for Core Data.

Ways to sync with iCloud

Apple offers more than one sync tool, and they solve different problems.

Three ways to sync

Key-value store A few small settings.
CloudKit mirroring A whole local database.
CloudKit directly Custom records and sharing.

Start with the smallest tool that fits.

1 / 2

iCloud key-value storage

NSUbiquitousKeyValueStore works like UserDefaults, but the values travel to the user's other devices. It is meant for a handful of small preferences or a "last read position". The total size is small (about 1 MB, and a limit of 1,024 keys), so it is not a place for documents or lists.

Swift
let cloud = NSUbiquitousKeyValueStore.default

cloud.set("dark", forKey: "theme")
cloud.synchronize()

NotificationCenter.default.addObserver(
    forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
    object: cloud,
    queue: .main
) { notification in
    // Another device changed a key: refresh the UI from `cloud`.
}

Conflicts here are simple: for a given key, the most recent write wins. That is fine for a theme choice and wrong for anything you must merge. You need the iCloud entitlement for the key-value store enabled for the target.

Mirroring a local database with CloudKit

NSPersistentCloudKitContainer is a subclass of NSPersistentContainer. You still read and write your local Core Data store as before. In the background, it copies changes to a private CloudKit database belonging to the user's iCloud account, and it pulls down changes made on other devices. The app works offline and syncs when it can.

Swift
let container = NSPersistentCloudKitContainer(name: "NotesModel")

let description = container.persistentStoreDescriptions.first!
description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(
    containerIdentifier: "iCloud.com.example.notes"
)
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)

container.loadPersistentStores { _, error in
    if let error { fatalError("\(error)") }
}
container.viewContext.automaticallyMergesChangesFromParent = true

The setup has several steps outside the code:

  1. Add the iCloud capability to the target and tick CloudKit, then create or choose a container.
  2. Add the Background Modes capability with Remote notifications, so the device wakes up when other devices push changes.
  3. Turn on history tracking, as in the code above, so changes can be merged.
  4. In development, the CloudKit schema is created for you the first time you run. Before release, you must deploy the schema to production in the CloudKit Dashboard. Forgetting this is a classic bug: sync works for you and for TestFlight builds but not for App Store users.

SwiftData can do the same with a configuration option: ModelConfiguration(cloudKitDatabase: .automatic) (or .none to keep a store local). It uses the same CloudKit machinery and the same limits.

The rules your model must follow

CloudKit is not a SQL database, so mirroring puts constraints on the model:

  • No unique constraints. Two devices could each create a record with the same "unique" value while offline.
  • Attributes must be optional or have a default value, because a record can arrive before all its fields do.
  • Relationships must be optional and have an inverse.
  • Deny delete rules are not supported.

These are the same rules that make a model migrate smoothly, so design for them from the start, even before you turn sync on. Retrofitting them later means a migration.

When you need more: CloudKit directly and sharing

Mirroring covers the private database. If you need to share records with other people (a shared shopping list), or you want public data that every user can read, you work with CloudKit itself: records, zones, subscriptions and CKShare. Core Data's CloudKit container supports sharing through its own API, which is another reason teams keep Core Data. This is a big topic of its own, so consider it a pointer rather than a recipe.

Designing for conflicts

You cannot prevent two devices from changing the same thing while offline, so decide what should happen. A conflict policy answers: when both sides changed the data, who wins?

  • Last writer wins on the whole record. Simple, and surprising: one device's edit to the title can erase another device's edit to the body.
  • Last writer wins per field. Better: each field keeps its own timestamp, so edits to different fields both survive.
  • Merge by meaning. A counter should add the changes, a set should take the union. This takes real design work.

In Core Data you choose the local merge behavior with a merge policy, for example NSMergeByPropertyObjectTrumpMergePolicy (in a clash, the in-memory object's property values win) or NSMergeByPropertyStoreTrumpMergePolicy (the stored values win). Both merge per property, which is why they usually beat NSOverwriteMergePolicy, which replaces whole objects. CloudKit mirroring applies its own rules on top, and in general you should assume that, for a single field, the most recent change wins.

The next example makes the difference between whole-record and per-field resolution visible. Two devices edit the same note while offline. Each field carries a logical timestamp, a plain integer, to keep the run deterministic.

Swift Whole-record vs per-field conflict resolution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Whole-record resolution keeps the tablet's version and the phone's new title vanishes. Per-field resolution keeps both edits. The last line shows an important property of a good merge: it gives the same result no matter which device merges first, so every device ends up with identical data.

Deletes are changes too

A delete must travel like any other edit, but a deleted record is gone, so there is nothing to compare. Sync systems therefore keep a small marker, a tombstone, that says "this record was deleted at time T". Without it, a device that was offline would see a record on its disk, find that the server does not have it, and could wrongly upload it again, resurrecting the note.

Swift Tombstones stop deleted notes from coming back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With the tombstone, the delete wins because it happened later than any edit to that note, and both devices agree on the result. The naive version has no way to tell "never had it" from "deleted it", so the milk comes back. CloudKit mirroring handles tombstones for you, but understanding them explains behavior users report: "I deleted it on my iPad and it showed up again" is nearly always a sync-design bug.

Practical advice for sync

  • Sync is eventual. Never block the UI on it. Show local data immediately and treat sync as a background detail.
  • The user may not be signed in to iCloud, or may have iCloud Drive turned off. The app must work fully without an account, and should not nag.
  • Test with two real devices or simulators signed in to the same account, with network on and off, and with conflicting edits.
  • Deploy the CloudKit schema before releasing, and keep changes to it additive: you cannot remove a field from production.
  • Do not put secrets or very large files in synced records. Use the Keychain for secrets (it has its own sync option) and CloudKit assets or files for big data.
  • Keep your own backup route for important user content, such as an export. Sync is not a backup: a delete propagates everywhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which situation is a good reason to choose Core Data over SwiftData?

    SwiftData requires iOS 17 or later. Core Data works on older systems and in existing apps.
  2. 2. What does NSPersistentCloudKitContainer do?

    You read and write the local store as usual; the container syncs changes to and from CloudKit in the background, so the app still works offline.
  3. 3. Which model rule is required for CloudKit mirroring?

    A record may arrive before all of its fields, and two offline devices could create the same unique value, so mirroring requires optional or defaulted attributes and forbids unique constraints.
  4. 4. Two devices edit different fields of one note while offline. Which strategy keeps both edits?

    Whole-record resolution keeps only one version. Per-field resolution compares each field on its own, so both edits survive.
  5. 5. Why do sync systems keep a tombstone for a deleted record?

    Without a marker, a device that still has the record cannot know whether the others deleted it or never had it, and may upload it again.

Summary

  • Core Data is the long-standing persistence framework behind SwiftData; it still matters for older iOS versions, existing apps and advanced features such as batch operations and sharing.
  • The iCloud key-value store syncs a few small settings; last write wins.
  • NSPersistentCloudKitContainer (or SwiftData's CloudKit option) mirrors a local store to the user's private CloudKit database and works offline.
  • Mirroring needs the iCloud and Background Modes capabilities, history tracking, a deployed production schema, and a model with optional or defaulted attributes, optional relationships and no unique constraints.
  • Decide your conflict policy: per-field merging beats whole-record overwriting, and a good merge gives the same result on every device.
  • Deletes need tombstones, sync is eventual, and sync is not a backup.

Next: Keychain, Biometrics and App Security