0

So I'm trying to sum values from a ForEach list using the following code:

@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Transaction.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Transaction.value, ascending: false)]) var fetchRequest: FetchedResults<Transaction>

var sum: Double {
    fetchRequest.reduce(0) { $0 + $1.value } //ERROR! 
    } 

Each time I run, there's an error:

[SwiftUI] Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x2813f2920>

USING PO:

(lldb) po fetchRequest
error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated

Here's the rest of the code:

var body: some View {
    NavigationView {
            Form {
                ...
                            Text("\(sum)")
                        }
                }
                ...

Can you help me find the error please?

  • 1
    Does this answer your question? [CoreData and SwiftUI: Context in environment is not connected to a persistent store coordinator](https://stackoverflow.com/questions/59166513/coredata-and-swiftui-context-in-environment-is-not-connected-to-a-persistent-st) – koen Aug 17 '20 at 13:46
  • No. I tried that way but it didn't work. I can't find where is not connected. – Luis Alessandro Vitte Soto Aug 17 '20 at 14:42
  • Just to be sure, did you enable CoreData when you created your project? All the Core Data setup code should be in `AppDelegate` and `SceneDelegate`, Make sure the container's name matches that of your project. – koen Aug 17 '20 at 15:14
  • Yes I did. Just to be clear, what should be or where can I find the containers name? I'm still a newbie in SwiftUI – Luis Alessandro Vitte Soto Aug 17 '20 at 15:36
  • That should have been set automatically. But you should have a line in AppDelegate similar to: `let container = NSPersistentContainer(name: "MyCoreDataModelName")`. There are many tutorials out there on this subject. And please update your title, it is not related to your problem at all. – koen Aug 17 '20 at 15:48
  • Okay I see and it does. I also updated the title, yet I've tried workarounds and nothing seems to work. Its always in sum: fetch request where I get the error. I don't know what I can do to fix this. – Luis Alessandro Vitte Soto Aug 17 '20 at 16:00
  • This is a good tutorial: https://www.raywenderlich.com/9335365-core-data-with-swiftui-tutorial-getting-started – koen Aug 17 '20 at 16:20
  • Thank you, that should do. I'll adapt that to my code. – Luis Alessandro Vitte Soto Aug 17 '20 at 21:37

0 Answers0