How can I get the fetch request from a different class so I can re-use it on different views and functions on other files? If you see on the code below, I have to call the fetch request twice in different classes, I want to create a class with a function called:
readData
so when I call it: readData()
it will return the @FetchRequest . I'm using SwiftUI. This is the code I was mentioning:import SwiftUI
struct ContentView: View {
@ObservedObject var myClass = MyClass()
@FetchRequest(
entity: ProgrammingLanguage.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \ProgrammingLanguage.id, ascending: true)
]
) var languages: FetchedResults
@Environment(\.managedObjectContext) var managedObjectContext
var body: some View {
NavigationView {
VStack {
List(languages, id: \.self) { language in
Text(self.language.name ?? "")
}
}
}
.onAppear{
// Data not refreshed
self.myClass.createData()
}
}
}
class MyClass: ObservableObject {
@FetchRequest(
entity: ProgrammingLanguage.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \ProgrammingLanguage.id, ascending: true)
]
) var languages: FetchedResults
@Environment(\.managedObjectContext) var managedObjectContext
func createData() {
for i in 1...5 {
let language = ProgrammingLanguage(context: self.managedObjectContext)
language.id = Int32(i) // << here !!
language.name = "\(i) SwiftUI"
do {
try self.managedObjectContext.save()
} catch {
}
}
}
func readData() {
// How can I return the objects here? Not in a loop, but as a fetch request so I can use that fetch request on other views
}
}