ios – 如何使用realm swift检索另一个对象列表中的对象?

我有一些看起来像这样的Realm类:

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>()
}

我明白要从领域中检索对象我必须这样做:

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

问题是:如何从’subs'(List)中检索对象?

最佳答案
检索主对象时,您可以像访问任何其他属性一样访问其子列表:

let subs = profile.subs

这为您提供了一个可以迭代的列表:

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

或者您可以过滤子类以查找特定对象:

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

或者您可以使用下标按索引访问元素:

let secondProfile = profile.subs[1]

转载注明原文:ios – 如何使用realm swift检索另一个对象列表中的对象? - 代码日志