NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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?

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.