Delete members of list when deleting list in Core Data / iOS / Swift 5

The credit for this goes to pbasdf for his super helpful responses. I used this link to learn about setting up relationships in Core Data: Seneca SDDS. I was missing one line in my persistence model:

newTask.list = newItem

How I solved this problem (in case it helps someone else) is that I created a one to many relationship for Item (the list of lists), and one to one relationship for Tasks (tasks are a subset of a list). Now, when I create a new task in the persistence script, I have a pointer back to the list it belongs to – hence the single line of code above.

The additional background that helped me understand Core Data relationships can be found in the link above. This snippet in particular was very helpful (in case the page goes 404):

Adding a new object, and setting the relationship Assume that you have a reference to a Company object already; its variable name is c. How do you add a new Employee or Product? Create the new object and set its relationship. The relationship can be configured from either direction. In this section, we will configure it from the perspective of the just-added new object. For example:

// As noted above, assume that you have a reference
// "c" to an existing Company object...

// Create and configure a new employee
let peter = Employee(context: m.ds_context) = "Peter McIntyre"
peter.age = 23
// etc.

// Now, set the relationship = c


That’s it. If it seems too easy, well, it is easy.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top