-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedsViewModel.swift
executable file
·70 lines (58 loc) · 2.34 KB
/
MedsViewModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// MedsViewModel.swift
// PainMedsBuddy
//
// Created by Jules Moorhouse.
//
import CoreData
import Foundation
extension MedsView {
class ViewModel: NSObject, ObservableObject, NSFetchedResultsControllerDelegate {
private let dataController: DataController
@Published var showingSortOrder = false
@Published var sortOrder = Med.SortOrder.optimised
private let medsController: NSFetchedResultsController<Med>
@Published var meds: [Med] = []
init(dataController: DataController) {
self.dataController = dataController
let medRequest: NSFetchRequest<Med> = Med.fetchRequest()
medRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Med.lastTakenDate, ascending: true)]
medRequest.predicate = !DataController.useHardDelete ? NSPredicate(format: "hidden = false") : nil
medsController = NSFetchedResultsController(
fetchRequest: medRequest,
managedObjectContext: dataController.container.viewContext,
sectionNameKeyPath: nil,
cacheName: nil
)
super.init()
medsController.delegate = self
do {
try medsController.performFetch()
meds = medsController.fetchedObjects ?? []
} catch {
print("ERROR: Failed to fetch our meds: \(error)")
}
}
func deleteMed(_ offsets: IndexSet, items: [Med]) {
for offset in offsets {
let med = items[offset]
let count = dataController.anyRelationships(for: [med])
// swiftlint:disable:next empty_count
if count == 0 && DataController.useHardDelete {
dataController.delete(med)
} else {
med.hidden = true
}
}
dataController.save()
dataController.container.viewContext.processPendingChanges()
}
func hasRelationship(med: Med) -> Bool {
dataController.hasRelationship(for: med)
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
print("### MedsViewModel - controllerDidChangeContent")
meds = medsController.fetchedObjects ?? []
}
}
}