-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFetchedResultsController.swift
More file actions
45 lines (39 loc) · 1.29 KB
/
FetchedResultsController.swift
File metadata and controls
45 lines (39 loc) · 1.29 KB
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
import CoreData
import Foundation
import SwiftData
@Observable
final class FetchedResultsController<T: PersistentModel> {
private(set) var models: [T] = []
private let modelContext: ModelContext
private let predicate: Predicate<T>?
private let sortDescriptors: [SortDescriptor<T>]
init(
modelContext: ModelContext,
predicate: Predicate<T>? = nil,
sortDescriptors: [SortDescriptor<T>] = []
) {
self.modelContext = modelContext
self.predicate = predicate
self.sortDescriptors = sortDescriptors
setupNotification()
}
func fetch() throws {
let fetchDesciptor = FetchDescriptor<T>(predicate: predicate, sortBy: sortDescriptors)
models = try modelContext.fetch(fetchDesciptor)
}
private func setupNotification() {
// Ideally we'd use the ModelContext.didSave notification but this doesn't seem to be sent.
// Last tested with iOS 17 beta 8 on September 4th, 2023.
NotificationCenter.default.addObserver(
self,
selector: #selector(didSave),
name: .NSPersistentStoreRemoteChange,
object: nil
)
}
@objc private func didSave(_ notification: Notification) {
do {
try fetch()
} catch {}
}
}