Skip to content

0.6.0

Compare
Choose a tag to compare
@spnkr spnkr released this 22 Feb 21:00
· 13 commits to main since this release
20cea52

What's Changed

  • Automatic creation and management of the Core Data stack by @spnkr in #7

Overview

Adds optional automatic creation and management of NSManagedObjectContexts so you don't have to create your own data access class or layer.

If you already have a data access layer, you can use that instead by implementing the new CoreDataContainer protocol.

Changes

  1. Adds CoreDataPlusStore
  2. Adds CoreDataContainer protocol
  3. New CoreDataPlus.setup(...) methods
  4. Makes CoreDataPlus.setup(...) throwable
  5. Updated example app to work without an AppDelegate

Notes

Add CoreDataPlusStore

  • CoreDataPlusStore automatically sets up NSManagedObjectContext's for your app.
  • It's a singleton, accessible via CoreDataPlusStore.shared
  • See Example App for UIKit and SwiftUI examples
  • To use your own class for managing NSManagedObjectContext's, implement CoreDataContainer in your class

How to use CoreDataPlusStore with SwiftUI:

@main
struct BestAppEver: App {

    let yourDataStore = CoreDataPlusStore.shared
    @Environment(\.scenePhase) private var phase

    init() {
        do {
            try CoreDataPlus.setup(store: CoreDataPlusStore.shared)
        } catch {
            NSLog(error.localizedDescription)
        }
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, yourDataStore.viewContext)
        }
        // save core data when the app goes into the background
        .onChange(of: phase) { newPhase in
            switch newPhase {
            case .background:
                try! yourDataStore.viewContext.save()
            default:
                break
            }
        }
    }
}

Add CoreDataContainer protocol

Use your own data access layer by implementing CoreDataContainer in that class.

public protocol CoreDataContainer {
    var viewContext: NSManagedObjectContext { get }
    var backgroundContext: NSManagedObjectContext { get }
}

Full Changelog: 0.5.1...0.6.0