Created
August 13, 2021 14:40
-
-
Save kpostekk/1e7c22f68021f0fd07ce7b481c1ffb11 to your computer and use it in GitHub Desktop.
Add CoreData to your SwiftUI using only one file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Persistence.swift | |
// | |
// | |
// Template from https://gist.github.com/kpostekk/1e7c22f68021f0fd07ce7b481c1ffb11 | |
// | |
import CoreData | |
struct PersistenceController { | |
static let shared = PersistenceController() | |
static var preview: PersistenceController = { | |
let pc = PersistenceController(inMemory: true) | |
let viewContext = pc.container.viewContext | |
// Whatever preview entities goes here | |
return pc | |
}() | |
let container: NSPersistentContainer | |
init(inMemory: Bool = false) { | |
container = NSPersistentContainer(name: "WhateverCoreDataName") | |
if inMemory { | |
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") | |
} | |
container.loadPersistentStores(completionHandler: { _, error in | |
if let error = error as NSError? { | |
// Whatever errors goes here | |
fatalError("Unresolved error \(error), \(error.userInfo)") | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment