Last active
November 26, 2022 19:15
-
-
Save southerton81/bdba2f659b39e1d82ff908f807b73d65 to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
import CoreData | |
final class CoreDataInventory { | |
static let instance = CoreDataInventory() | |
let persistentContainer: NSPersistentContainer | |
let viewContext: NSManagedObjectContext | |
private let backgroundContext: NSManagedObjectContext | |
private init() { | |
persistentContainer = NSPersistentContainer(name: "Data") | |
persistentContainer.loadPersistentStores { _, error in | |
if let error = error as NSError? { | |
fatalError("Unresolved error \(error), \(error.userInfo)") | |
} | |
} | |
viewContext = persistentContainer.viewContext | |
viewContext.automaticallyMergesChangesFromParent = true | |
backgroundContext = persistentContainer.newBackgroundContext() | |
} | |
/* Performs supplied block on a background managed object context | |
and saves possible changes */ | |
func perform(block: @escaping (_ context: NSManagedObjectContext) -> Void) async { | |
await backgroundContext.perform { | |
do { | |
block(self.backgroundContext) | |
if (self.backgroundContext.hasChanges) { | |
try self.backgroundContext.save() | |
} | |
} catch { | |
let nsError = error as NSError | |
fatalError("saveContext() error: \(nsError), \(nsError.userInfo)") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment