eeschimosu
eeschimosu

Reputation: 643

How to retrieve an object that is in a list in another object using realm swift?

I have some Realm classes that look like this:

class Friends: Object {
    dynamic var name = true
    dynamic var role = true
    dynamic var type = true
    dynamic var owner: Profile?
}

class Profile: Object {
    dynamic var uuid = NSUUID().UUIDString
    dynamic var name = ""
    dynamic var date = NSDate(timeIntervalSinceNow: 1)
    dynamic var section = 0
    dynamic var code = ""
    dynamic var gender = 0
    dynamic var type = ""
    let friends = List<Friends>()

    override static func primaryKey() -> String? {
       return "uuid"
    }
}

class Sub: Profile {
    dynamic var owner: Master?
}

class Master: Object {
    dynamic var type = ""
    dynamic var name = ""
    dynamic var date = ""
    let subs = List<Sub>()
}

I understand that to retrieve the objects from realm I have to do this:

var master = try! Realm().objects(Master)
let profile = master[indexPath.row]
let date = profile.date
let name = profile.name
let type = profile.type

The question is: How do I retrieve objects from the 'subs'(List) ?

Upvotes: 3

Views: 3305

Answers (1)

joern
joern

Reputation: 27620

When you retrieve a master object you can access its subs list like any other property:

let subs = profile.subs

This gives you a list that you can iterate over:

for sub in profile.subs {
    // do something with the sub object
}

Or you can filter the subs to find a particular object:

if let subjectWithId = profile.subs.filter("uuid == '7382a8d83'").first {
    // do something with the subject
}

Or you can use subscripting to access elements by index:

let secondProfile = profile.subs[1]

Upvotes: 7

Related Questions