0

I'm having a problem with new SwiftUI. I created CoreData models Cars and Datepoints with a one-to-many relationship (one car -> many datepoints). Therefore I need a fetch request for gathering all datepoints of a car. How am i doing this?

Have a look at my current code for gathering just the cars. Can I modify @FetchRequest to reach that?

 @FetchRequest(entity: Cars.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Cars.name, ascending: true)]) var cars: FetchedResults<Cars>
RPatel99
  • 7,448
  • 2
  • 37
  • 45
calli23
  • 79
  • 9
  • Datepoints is a property on Cars with the same name as the name of the relationship in your model. So if the relationship is datepoints then you can access them as `for car in cars { print(car.datepoints) }` – Joakim Danielson Oct 21 '19 at 08:51

2 Answers2

1

You can use a predicate in the fetchRequest for datapoints. Here an example how it could look like:

 @FetchRequest(
    entity: Datapoints.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \Datapoints.date, ascending: true),
    ],
    predicate: NSPredicate(format: "CarsRelationship.name == %@", "Ford")
) var datapoints: FetchedResults<Datapoints>

Here you can find more basic information on CoreData and SwiftUI: https://www.hackingwithswift.com/quick-start/swiftui/how-to-filter-core-data-fetch-requests-using-a-predicate

HeGe
  • 63
  • 6
-1

To build up on @HeGe’s answer and show an actual example, a good way is to create a custom initializer in your view and use that to do the fetch request.

Here’s an example I copied over from a different question by Gene Bogdanovich which perfectly shows this in action:

struct MyListView: View {
    let car: Car
    
    @FetchRequest private var datapoints: FetchedResults<Datapoint>
    
    init(car: Car) {
        self.car = car
        
        _datapoints = FetchRequest(
            entity: Datapoint.entity(),
            sortDescriptors: [NSSortDescriptor(keyPath: \ Datapoint.name, ascending: true)],
            predicate: NSPredicate(format: "relatedCar == %@", car)
        )
    }
    
    var body: some View {
        List {
            ForEach(datapoints) { datapoint in
                Text("\(datapoint.name ?? "")")
            }
        }
    }
}

In order for this to work the NSPredicate(format: "relatedCar == %@", car) of course has to match the naming of your Core Data model. So in this example the Datapoint entity has a relationship called „relatedCar“ of the destination Car.

alexkaessner
  • 1,966
  • 1
  • 14
  • 39