2
votes

I am currently working with CoreData.

Problem: I have a CoreData Entity User with a one-to-many-relationship to another CoreData Entity Badges. I am now trying to delete a User and, obviously, also would like to delete all of his Badges.

Deleting the User itself is pretty straight forward:

context.delete(selectedUser)

However I have to first delete all of the User's Badges. This is the complicated Part for me:

for badge in selectedUser.badges {
    context.delete(badge)
}

When doing so, this Error occurs: Cannot convert value of type 'NSSet.Element' (aka 'Any') to expected argument type 'NSManagedObject'

My Possible Solution: I was thinking of simple downcasting: context.delete(badge as! NSManagedObject). However I am not sure whether this is possible.

Question: What is the best Practice for achieving the Goal I described above? Or is there maybe a CoreData way to recursively delete all related Objects?

Thanks for your help.

1
Just set the "Deletion Rule" for the relationship to "Cascade". Compare stackoverflow.com/q/20528011/1187415.Martin R
@MartinR thanks for your answer. This does work perfectly and is much more clean than my approach. Just for Interest: Can you downcast NSSet.Element to NSManagedObject?christophriepe
Yes, you can...Martin R
@MartinR Feel free to post this as your answer so that I can accept it.christophriepe

1 Answers

1
votes

selectedUser.badges is an NSSet of Badges, therefore you can cast its elements to Badge or to NSManagedObject:

for badge in selectedUser.badges {
    context.delete(badge as! NSManagedObject)
}

You can also cast the NSSet to its Swift counterpart Set:

for badge in selectedUser.badges as! Set<Badge> {
    context.delete(badge)
}

But in order to delete all related objects if a user is deleted, the simple solution is to set the “Deletion Rule” for the relationship to “Cascade”.