使用Realm Swift计算嵌套对象的出现次数

时间:2017-11-10 15:15:36

标签: ios swift realm

我有这个Movie模型,我将Actor作为嵌套对象:

@objcMembers class Movie: Object, Mappable {

    dynamic var _id: String? = nil
    dynamic var actors = List<Actor>()
    // more stuff

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

当我从服务器上取电影并将它们添加到我的Realm(使用Alamofire - &gt; ObjectMapper - &gt; RealmSwift)时,如何在这些Actor中找到代表性最高的Results<Movie>

即。 Nicolas Cage在我的整部电影收藏中播放了30部电影。他是最具代表性的演员。

我如何“计算”演员尼古拉斯凯奇作为我的电影的嵌套对象的出现?

我已经用普通的Swift实现了这个目标,但我想知道是否有一种优雅的方式可以用Realm Swift来做到这一点。

提前致谢✌

PS:抱歉选择不好的演员。

1 个答案:

答案 0 :(得分:2)

其中一种可能的解决方案是依靠Realm的内置功能并使用反向关系。

只需将反比关系添加到Actor模型类中即可。 actedIn将包含对所有Movie个对象的引用,这些对象在Actor属性中包含actors个实例。

在寻找拥有大多数电影的演员时,您只需要从您的Realm中获取所有演员,然后使用内置的max(by:)函数找到actedIn具有最多元素的演员。

@objcMembers class Actor: Object {
    dynamic var name = ""
    let actedIn = LinkingObjects(fromType: Movie.self, property: "actors")
}

@objcMembers class Movie: Object {
    dynamic var _id: String? = nil
    dynamic var actors = List<Actor>()

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

//Generate test data
try! realm.write {
    let nicholasCage = Actor(value:["name":"Nicholas Cage"])
    let adamSandler = Actor(value:["name":"Adam Sandler"])
    let jessicaBiel = Actor(value:["name":"Jessica Biel"])
    let nicoleKidman = Actor(value:["name":"Nicole Kidman"])
    realm.add([nicholasCage,adamSandler,jessicaBiel,nicoleKidman])
    let firstMovie = Movie()
    firstMovie.actors.append(objectsIn: [nicholasCage,nicoleKidman])
    firstMovie._id = "first"
    let secondMovie = Movie()
    secondMovie.actors.append(objectsIn: [nicholasCage,adamSandler])
    secondMovie._id = "second"
    let thirdMovie = Movie()
    thirdMovie.actors.append(objectsIn: [nicholasCage,nicoleKidman,jessicaBiel])
    thirdMovie._id = "third"
    realm.add([firstMovie,secondMovie,thirdMovie])
}

let allActors = realm.objects(Actor.self)
let actorWithMostMovies = allActors.max(by: {$0.actedIn.count < $1.actedIn.count})
actorWithMostMovies?.name //"Nicholas Cage"
actorWithMostMovies?.actedIn.count //3