简体   繁体   中英

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

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

In mapper,

(map["key"], ArrayTransform<Object>())

"key" is JSON key

"Object" is your custom object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM