Alexnnd
Alexnnd

Reputation: 769

Core Data relationship is complicated

I tried the great tutorial from Paul Hudson to have a look at the Core Data relationship: https://www.hackingwithswift.com/books/ios-swiftui/one-to-many-relationships-with-core-data-swiftui-and-fetchrequest and everything worked like a charm.

But unfortunately this isn't what I really need and when I make some changes it's not working like I'd love to!

Here's what I'm trying to make:

VStack {
    ForEach(countries) { country in
        HStack {
            Text(country.wrappedFullName)
            Spacer()
            Button("Add") {

                // I'd love to add a candy from here
                // And based on the "id" and not the "shortName"

                let candy = Candy(context: moc)
                candy.id = UUID()
                candy.date = Date()
                candy.name = "Example"

                candy.origin = Country(context: moc) // I have to repeat that?
                candy.origin?.id = UUID() // This isn't right!

                try? moc.save()

            }
        }
    }
}

And then, in another screen (SwiftUI View), I list every candies from the selected country.

So what am I doing wrong? Do you know a simple solution to this problem? Thanks in advance. ✌️

Upvotes: 0

Views: 353

Answers (1)

HunterLion
HunterLion

Reputation: 4006

You first need to have a Country object to assign as the origin of the Candy.

Here are the steps:

// Create the Candy
let candy = Candy(context: moc)
candy.id = UUID()
candy.date = Date()
candy.name = "Example"

// Create the Country
let country = Country(context: moc)
country.id = UUID()
country.name = "Swiftland"

// Link both
candy.origin = country

try? moc.save()

(Edit) Note: the code above is just to exemplify the creation of a relationship between two Core Data objects. It should not be used "as-is" inside the Button in the question, as it would create new candies and countries at every hit. Place each part of the code above where appropriate to avoid duplicates.

Upvotes: 1

Related Questions