skip to content

In Core Data, how do you move an app's SQLite store into an app group so its widget extension can open the same file?

level: middleimportance: should knowfreq 40%

answer

  1. the widget has its own sandbox
  2. the same App Group on both targets
  3. containerURL(forSecurityApplicationGroupIdentifier:)
  4. override defaultDirectoryURL()
  5. the -wal file travels with the store

basics

~20 s

Give the app and widget the same App Group, open the store at a URL inside its container, and move existing users' store there once with the coordinator's replacePersistentStore and destroyPersistentStore, never a FileManager copy of the .sqlite file alone.

solid answer

~40 s

A widget extension is a separate process with its own sandbox, so `defaultDirectoryURL()` in the widget points somewhere the app's store isn't. Add the same App Group to both targets and open the store inside the group container: either set the description's `url` to a file under `FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:)`, or subclass `NSPersistentContainer` and override `defaultDirectoryURL()` so both targets resolve the same folder. Users who already have a store need a one-time move before the container loads: `NSPersistentStoreCoordinator`'s `replacePersistentStore(at:destinationOptions:withPersistentStoreFrom:sourceOptions:type:)`, then `destroyPersistentStore(at:type:options:)` on the old URL. A SQLite store keeps recent transactions in its `-wal` file, so copying only the `.sqlite` file can open without an error and still be missing rows.

code

swift · 23 lines
swift
import CoreData

final class SharedPersistentContainer: NSPersistentContainer, @unchecked Sendable {
    // Both the app and the widget extension create this subclass, so both
    // open <app group>/FieldSales.sqlite instead of their own sandboxes.
    override class func defaultDirectoryURL() -> URL {
        guard let url = FileManager.default.containerURL(
            forSecurityApplicationGroupIdentifier: "group.com.example.fieldsales") else {
            preconditionFailure("App Groups entitlement missing for this target")
        }
        return url
    }
}

// One-time move for users whose store predates the app group.
func moveStoreIfNeeded(from oldURL: URL, to newURL: URL, model: NSManagedObjectModel) throws {
    let files = FileManager.default
    guard files.fileExists(atPath: oldURL.path), !files.fileExists(atPath: newURL.path) else { return }
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
    // Copies the store together with its -wal and -shm files, then truncates the old one.
    try coordinator.replacePersistentStore(at: newURL, withPersistentStoreFrom: oldURL, type: .sqlite)
    try coordinator.destroyPersistentStore(at: oldURL, type: .sqlite)
}

go deeper

for a junior

Recall that an extension has its own sandbox, so a shared store has to live in an app group container both targets can reach.

for a middle

Explain the two ways to point the stack there, a description URL or a subclass overriding defaultDirectoryURL(), and why a nil group URL must not fall back silently.

for a senior

Move existing stores with replacePersistentStore and destroyPersistentStore before loading, and explain how a plain file copy loses rows held in the -wal file.

for a principal

Plan the move as a one-time, tested launch step for every installed version, and keep a single shared stack setup so app and widget can't drift on URL or options.

## Why the widget can't see the store On iOS every app and every extension runs in its own sandbox. `NSPersistentContainer` puts its store in `defaultDirectoryURL()`, a directory inside the sandbox of whichever process is running, so the widget's container looks in the widget's own directory and finds no store, or creates an empty one. To share data, both processes have to open **the same file**, and the only place both can reach is an **app group container**. ## Pointing both targets at the group container - Add the **App Groups** capability with the same group identifier to the app target and the widget extension target. - Get the folder with `FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:)`. On iOS it returns `nil` when the identifier isn't valid for the target, which almost always means the entitlement is missing. - Either set `url` on the container's store description to a file inside that folder, or subclass `NSPersistentContainer` and override the class method `defaultDirectoryURL()`, which Apple documents as overridable. A subclass keeps every target on the same location without repeating the URL logic. - Use the same store file name in both targets; the container name decides it (`FieldSales.sqlite`). - Don't fall back to the app's own directory when the group URL is `nil`. The app and widget would then quietly open two different stores and drift apart with no error anywhere. The store's data protection class is a store option too: `NSPersistentStoreFileProtectionKey` defaults to complete-until-first-user-authentication for apps built for iOS 5 or later, so the widget can open the store once the device has been unlocked after a restart. Protection classes in general belong with FileManager. ## Moving existing users' data People updating from a version without the app group already have a store in the old location. Move it **before** loading the container: 1. Check that the old store exists and that nothing is at the new URL yet. 2. Create a bare `NSPersistentStoreCoordinator` with the model. 3. Call `replacePersistentStore(at:destinationOptions:withPersistentStoreFrom:sourceOptions:type:)` with the new URL as destination and the old URL as source. 4. Call `destroyPersistentStore(at:type:options:)` on the old URL. 5. Load the container at the new location as usual. | Approach | What happens to the sidecar files | Result | |---|---|---| | `FileManager` copy or move of `FieldSales.sqlite` alone | The `-wal` and `-shm` files stay behind | The copy can open cleanly yet lack recent rows still held in the `-wal` file | | `replacePersistentStore(at:destinationOptions:withPersistentStoreFrom:sourceOptions:type:)` | Core Data handles the journal files, locks and journal mode | A complete store at the new URL | | `destroyPersistentStore(at:type:options:)` on the old URL | Truncates the old store rather than unlinking it | The old store is empty; its files may remain | The headers explain both choices. SQLite stores "honor file locks, journal files, journaling modes" during replace and destroy, and because a database file can't be unlinked safely from under another thread or process, destroy truncates it. Core Data creates SQLite stores in WAL mode by default, which is why recent transactions can sit in the `-wal` file rather than the main file. ## What sharing the file does not give you The app and the widget each build their own container and coordinator over the shared file; one container instance can't be shared between processes. Two things follow: - Both must open the store with the **same options**. In particular a store opened once with persistent history tracking must always be opened with it, or Core Data opens it read-only. - Neither process learns about the other's saves on its own. Seeing the widget's writes in the app takes persistent history tracking and remote change notifications, which is its own topic within the stack. ## Testing the move - Install the previous release, create data, then install the new build over it and confirm every row arrives in the group container. - Run the move twice: the existence checks must make the second launch a no-op. - Launch the widget before the app has run the move once, and decide what it shows while the shared store doesn't exist yet. What to keep in a widget's store, and whether a widget should read the database at all, is a design choice for the system design material on local storage.

  • Why not fall back to the app's own directory when containerURL(forSecurityApplicationGroupIdentifier:) returns nil?
    Then the app and the widget silently open two different stores: the widget shows empty or stale data and nothing reports an error. On iOS a nil URL means the group identifier isn't valid for that target, a setup bug worth failing loudly on during development.
  • Why can the old store's files still be there after destroyPersistentStore(at:type:options:)?
    For SQLite the call truncates the store instead of unlinking it, because a database file can't be removed safely while another thread or process might hold it. The old store is empty afterwards even if its files remain on disk.
  • Can the app and the widget share one NSPersistentContainer instance?
    No. They are separate processes, so each builds its own container and coordinator over the same file. What they must agree on is the store URL and the store options, such as persistent history tracking; neither sees the other's saves without it.

  • Copying FieldSales.sqlite with FileManager moves all of the user's data.
  • The widget can read the app's Application Support folder directly.
  • The app and its widget can share one NSPersistentContainer instance.
  • destroyPersistentStore(at:type:options:) always deletes the store's files from disk.
  • containerURL(forSecurityApplicationGroupIdentifier:) creates the group when it's missing.