Search code examples
iosswiftrealm

iOS - Appending element to list in realm does not persist element


I am adding a song to a List in my Playlist object with the following code:

func addSongsForPlaylist(songs: [Song], list: Playlist) {
    try! realm!.write {
        for song in songs {
            list.RLMsongs.append(song)
        }
    }
}

Where songs is just an array of the songs that I want to add. The songs in songs are non persisted objects (not in realm yet), but list is already persisted in Realm.

I have found quite a few questions here on stackoverflow that seem to ask the same question but all their solutions were having to do with wrapping the append in a write transaction which I am already doing as you can see.

I have also tried the following:

try! realm!.write {
    list.RLMsongs.appendContentsOf(songs)
}

What is happening is that if I enter po list.RLMsongs in the console the new song is there and it looks great, but if I enter po list its RLMsongs property is missing the new song. How can both be true? It seems to contradict itself and seems like there is something fundamental that I am missing about RealmSwift.

It looks like it is updating the list in memory but not actually committing to Realm. Therefore, I thought maybe the write block was not committing properly and wrapped it in a do catch but the catch is never run so the write transaction should be successfully committing.

EDIT:

Also, I noticed that I am able to remove the write transaction and it DOES NOT give me an error. I think this could be a clue as to what is going on here. Is it possible that the List is considered non persisted and therefore does not update properly in realm at all even though the contents of the list (the songs) are persisted objects?


Solution

  • Turns out that my issue was that I had to re-fetch the Playlist from realm...somehow the Playlist as it was passed into the function was not being considered a valid persisted object in realm. (Even though I have other update functions that work the same way that update other properties instead of appending objects to the song list and those update functions work fine)

    My only guess is that something to do with appending to a list inside of a persisted object somehow works differently and the list must be explicitly fetched within the local scope and not just passed in as a function parameter. I could be wrong about this however. I just know this is how I got it to work on my end.