57 lines
1.4 KiB
Swift
57 lines
1.4 KiB
Swift
import Foundation
|
|
import CoreData
|
|
|
|
protocol StorageServiceProtocol {
|
|
|
|
var context: NSManagedObjectContext { get }
|
|
func store(vehicle: Vehicle) throws -> CDVehicle
|
|
}
|
|
|
|
class StorageService: StorageServiceProtocol {
|
|
|
|
private let container: NSPersistentCloudKitContainer
|
|
|
|
static let shared = StorageService()
|
|
|
|
init(inMemory: Bool = false) {
|
|
|
|
container = NSPersistentCloudKitContainer(name: "AutoCat2")
|
|
if inMemory {
|
|
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
|
|
}
|
|
|
|
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
|
|
if let error = error as NSError? {
|
|
// TODO: Handle error properly
|
|
fatalError("Unresolved error \(error), \(error.userInfo)")
|
|
}
|
|
})
|
|
}
|
|
|
|
private func save() throws {
|
|
guard context.hasChanges else {
|
|
return
|
|
}
|
|
|
|
do {
|
|
try context.save()
|
|
} catch {
|
|
context.rollback()
|
|
throw error
|
|
}
|
|
}
|
|
|
|
// MARK: - StorageServiceProtocol
|
|
|
|
var context: NSManagedObjectContext {
|
|
container.viewContext
|
|
}
|
|
|
|
func store(vehicle: Vehicle) throws -> CDVehicle {
|
|
|
|
let cdVehicle = CDVehicle(vehicle: vehicle, context: context)
|
|
try save()
|
|
return cdVehicle
|
|
}
|
|
}
|