Search code examples
swiftcore-dataentitynsmanagedobjectnsset

When deleting a CoreData Object, how to also delete all of its related Objects in Swift5?


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.


Solution

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