2

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.

4
  • 1
    Just set the "Deletion Rule" for the relationship to "Cascade". Compare stackoverflow.com/q/20528011/1187415.
    – Martin R
    Nov 28, 2020 at 10:50
  • @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? Nov 28, 2020 at 11:03
  • Yes, you can...
    – Martin R
    Nov 28, 2020 at 11:11
  • 1
    @MartinR Feel free to post this as your answer so that I can accept it. Nov 28, 2020 at 11:13

1 Answer 1

2

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”.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.