Relationships question


#1

Swift and Realm newbie here. I must be missing something obvious. I have 2 objects in a many to many relationship set up like this:

class Song: Object {
@objc dynamic var title = “”
@objc dynamic var lastEdit = Date()
@objc dynamic var dateFinished: Date? = nil
@objc dynamic var dateCreated = Date()
let lyrics = List()
}

class Lyrics: Object {
@objc dynamic var lastEdited = Date()
@objc dynamic var lyric = “”
@objc dynamic var placement = “”
@objc dynamic var rating = 0
@objc dynamic var section = “”
let song = LinkingObjects(fromType: Song.self, property: “lyrics”)
}

I’m adding data like this.

let song = Song()
let lyrics = Lyrics()

song.title = “Song Title”
song.dateCreated = Date()
song.lastEdit = Date()

lyrics.section = “Verse 1”
lyrics.rating = 2
lyrics.lastEdited = Date()
lyrics.lyric = “blah blah blah”
lyrics.placement = “1”

try! realm.write {
realm.add(lyrics)
realm.add(song)
}

This mostly works. Realm Studio says the data is all there. What isn’t there are the relationships. How do I tell the song which lyrics are related and visa versa? I swear I’ve read through the docs more than once, it’s just not clicking in my brain.


#2

The reason is that you don’t set the actual relationship.
try this:

song.lyrics.add(lyrics)

Then in the realm.write you need to only add the song :wink:


#3

I don’t seem to have an .add method but I have an .append and now I have a relationship from song to lyrics. I am not seeing the reverse in Realm Studio but in code it looks like there is a relationship that way as well. I take it that is normal?

Thanks a ton for the help.