Home > Software design >  Accessing and looping on Core Data from the app's @main class
Accessing and looping on Core Data from the app's @main class

Time:06-22

I have a simple Core Data macOS app, with its Data Model as follow:

Entity:
Data

Attributes:
text     String
starred  Boolean
date     Date 

I'm trying to access the data from a custom menu I created, iterate it and (in the future) save it to disk.

I've been trying to add code directly to the menu item created as:

@main
struct My_DataApp: App {
    let persistenceController = PersistenceController.shared
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
                .frame(minWidth: 560, maxWidth: .infinity,
                       minHeight: 300, maxHeight: .infinity)
                .onAppear {
                    NSWindow.allowsAutomaticWindowTabbing = false
                }
        }
        .windowToolbarStyle(UnifiedWindowToolbarStyle(showsTitle: false))
        .commands{
            CommandGroup(after: CommandGroupPlacement.newItem) {
                Button("Export Data") {
                    @FetchRequest(entity: Data.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Data.date, ascending: false)], animation: .default)
                    var DataItems: FetchedResults<Data>
                    for data in DataItems {
                        print("\(String(describing: data.text))")
                    }

                }                
            }
        }

    }
}

Of course Xcode is complaining:

enter image description here

I understand the error but I don't know how else to think about accessing the data from the menu.

I saw a few posts here in SO about the same error, and I tried to add code to the .onAppear section but same error happens there.

Thanks for any help.

CodePudding user response:

You can use NSFetchRequest directly and execute it by view context, like

Button("Export Data") {

  let fetchRequest = Data.fetchRequest()
  // .. set up parameters

  let context = self.persistenceController.container.viewContext
  if let result = try? context.fetch(fetchRequest) {
    for data in result {
        print("\(String(describing: data.text))")
    }
  }
}                
  • Related