Search code examples
iosswiftcore-dataswift5cascade

Coredata Delete Parent record when there is no children in swift 5


I have an AlbumDB(Parent) and SongInfoDB(Children's). When there no children's then I need to remove a parent as well means AlbumDB.

enter image description here

Here in the image, I need to remove AlbumDB when there is no SongInfoDB. In other words, when I remove all songs then automatically album will be removed.

I checked some of StackOverflow link and try core data delete rule as well. Nullify, Cascade, Deny but none of these worked for me!

Is there any suggestion regarding this. Thank You!


Solution

  • There is no automatic way. You can delete children automatically if the parent object was deleted but not vice versa.

    A posible solution is to create a function which deletes the song, then checks if the album (the relationship) is empty and if so deletes also the album.

    Something like

    func deleteSong(_ song : Song) {
        context.delete(song)
        let album = song.album!
        if album.songs.isEmpty {
            context.delete(album)
        }
        context.save()
    }