Nathaniel
Nathaniel

Reputation: 70

Swift 4 Core Data - Fetching Relationships

I have entities as so:

Entity 1

Entity 2

I am saving data as so:

@IBAction func saveButton(_ sender: UIButton) {
    print("save")
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let context = appDelegate.persistentContainer.viewContext
    let workout = Workout(context: context)
    workout.name = workoutName.text
    workout.noOfSets = Int16(setsStepper.value)

    for index in 0..<setsVal {
        let sets = Sets(context: context)
        let test = IndexPath(row: index, section: 0)
        let cell = tableView.cellForRow(at: test) as! RepsTableViewCell
        sets.repAmount = Int16(cell.repsStepper.value)
        // Does this line not create the relationship between Workout and Set Entities?
        workout.addToSets(sets)
    }
    try! context.save()
}

And I am fetching data as so:

func fetch() {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let context = appDelegate.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Workout")
    request.relationshipKeyPathsForPrefetching = ["Sets"]

    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            print(data.value(forKey: "name") as! String)
            print(data.value(forKey: "noOfSets") as! Int16)
        }
    }
    catch {
        print("failed")
    }
}

I've set up the relationship between entities Workout and Sets as one-many, yet cannot retrieve Set's attributes from Workout.

How can I retrieve an entities relationship attributes?

Do I need to specify the relationship programmatically despite the relationship being setup in the xcdatamodel file?

Does Workout.addToSets(sets) create the relationship between the entities?

Upvotes: 2

Views: 1745

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51945

You should be able to access your relationship entities as an attribute so for instance

for workout in result as! [Workout] {
    print(workout.name)
    if let sets = workout.sets { //assuming you have name your to-many relationship 'sets'
        print(sets.count)
    }
}

Upvotes: 2

Related Questions