UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

pass core data results to function in another class

Forums > SwiftUI

MVVM is hard. I'm trying to setup MVVM for my view. Specifically I have a ist of rows for an entity, The rows are the result of

  @FetchRequest(sortDescriptors: [SortDescriptor(\.name)]) var players: FetchedResults<Player>

I have a ForEach in a List to get the view and I can delete rows. I added

      .onDelete() { indexSet in
        removePlayers(at: indexSet)
      }

and

   func x (a: FetchedResults<Player>) {

  }

 func removePlayers(at offsets: IndexSet) {
    for index in offsets {
      let player = players[index]
      moc.delete(player)
    }
    try? moc.save()
    x(a: players)
  }

This works fine. When I move this to another class, in another source member, I get a problerm

    func removePlayers(at offsets: IndexSet, players:  FetchedResults<Player>, moc: NSManagedObjectContext) {
      for index in offsets {
        let player = players[index]
        moc.delete(player)
      }
      try? moc.save()
    }

I get an error "Cannot find type 'FetchedResults' in scope" on the func line. The view structure contains a function, x, that has the result set as a parameter and the compiler is happy with that. I did a copy/paste to move the parameter desctiption, so they are spelled the same.

Both files have the same Import, I added Import CoreData in hopes of fixing it but it still fails.

I have two questions. First, why is the type FetchedResults found in one file and not the other. Two, is there an easier way to move the delete to a MVVM module. As far as I know the delete needs the moc and the fetched result. Both of those things are in the view structure. I tried moving the @FetchRequest and extracting the moc from the environment to the MMVM class, but that had problems.

So, do I leave delete in the view structure, go about getting access to stuff other than passing them as parameters, or pass the FetchResult differently?

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.