Mercurial > public > geoquiz
comparison GeoQuiz/Models/Controllers/PersistenceController.swift @ 26:425078c01194
refactor code
author | Dennis C. M. <dennis@denniscm.com> |
---|---|
date | Wed, 09 Nov 2022 10:30:01 +0100 |
parents | GeoQuiz/Logic/PersistenceController.swift@02dcebb8cc4a |
children |
comparison
equal
deleted
inserted
replaced
25:b3df0f5dc750 | 26:425078c01194 |
---|---|
1 // | |
2 // PersistenceController.swift | |
3 // GeoQuiz | |
4 // | |
5 // Created by Dennis Concepción Martín on 19/10/22. | |
6 // | |
7 | |
8 import CoreData | |
9 import SwiftUI | |
10 | |
11 class PersistenceController { | |
12 static let shared = PersistenceController() | |
13 | |
14 let container: NSPersistentCloudKitContainer | |
15 | |
16 static var preview: PersistenceController = { | |
17 let result = PersistenceController(inMemory: true) | |
18 let viewContext = result.container.viewContext | |
19 | |
20 #if DEBUG | |
21 createMockData(with: viewContext) | |
22 #endif | |
23 | |
24 return result | |
25 }() | |
26 | |
27 init(inMemory: Bool = false) { | |
28 container = NSPersistentCloudKitContainer(name: "GeoQuiz") | |
29 | |
30 if inMemory { | |
31 container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") | |
32 } | |
33 | |
34 container.loadPersistentStores(completionHandler: { (storeDescription, error) in | |
35 if let error = error as NSError? { | |
36 fatalError("Unresolved error \(error), \(error.userInfo)") | |
37 } | |
38 }) | |
39 | |
40 container.viewContext.automaticallyMergesChangesFromParent = true | |
41 } | |
42 | |
43 #if DEBUG | |
44 static func createMockData(with moc: NSManagedObjectContext) { | |
45 for _ in 0..<10 { | |
46 let playedGame = PlayedGame(context: moc) | |
47 | |
48 playedGame.type = GameType(rawValue: Int16.random(in: 0...3))! | |
49 playedGame.score = Int32.random(in: 0...50) | |
50 | |
51 let dayComponent = DateComponents(day: Int.random(in: -5...0)) | |
52 playedGame.date = Calendar.current.date(byAdding: dayComponent, to: Date()) | |
53 | |
54 if playedGame.type == .guessTheFlag || playedGame.type == .guessTheCapital { | |
55 playedGame.correctAnswers = ["Bangladesh", "Belgium", "Burkina Faso", "Bermuda", "Jamaica"] | |
56 playedGame.wrongAnswers = ["Belarus", "Russia"] | |
57 } else { | |
58 playedGame.correctAnswers = ["Herat", "Lobito", "Darregueira", "San Juan"] | |
59 playedGame.wrongAnswers = ["San Luis", "Oranjestad"] | |
60 } | |
61 } | |
62 do { | |
63 try moc.save() | |
64 } catch { | |
65 let nsError = error as NSError | |
66 fatalError("Unresolved error \(nsError), \(nsError.userInfo)") | |
67 } | |
68 } | |
69 #endif | |
70 } |