Search code examples
iosarraysrealm

Storing an array of Realm objects inside another Realm object (Swift)


Im creating a music like app. So far I am able to create and save song objects and save them to realm. The song objects are made up of simple "songTitle" and "songArtist" string variables.

I would like to add playlist-like functionality and I believe the best way would be through arrays. The playlist object would contain a "songsInPlaylist" array and that array would be populated with a list of previously created song objects. I have looked over the documentation and I cant get a lead on where to start.

In short, how do you create a realm object that contains an array of other realm objects.

I am using Swift 2.0

Click to see visual representation...


Solution

  • Using array of Realm Objects is simple, just use List container data structure to define to-many relation. Check this example:

    class Task: Object {
    
       dynamic var name = ""
       dynamic var createdAt = NSDate()
       dynamic var notes = ""
       dynamic var isCompleted = false
    }
    
    class TaskList: Object {
    
       dynamic var name = ""
       dynamic var createdAt = NSDate()
       let tasks = List<Task>()
     }
    

    You can have a look to my sample Todo app using Ream in Github