Realm 没有可以完全做到这一点的本机查询,但是您可以将 Realm 的 KVC 支持与NSCountedSet结合起来相当容易地实现这一点:
import Foundation
import RealmSwift
class MyObject: Object {
dynamic var id: Int = 0
dynamic var val: String = ""
}
let realm = try! Realm()
try! realm.write {
for (index, value) in ["A", "B", "A", "B", "A", "A"].enumerate() {
realm.create(MyObject.self, value: [index, value])
}
}
let values = realm.objects(MyObject).valueForKey("val") as! [AnyObject]
let countedSetOfValues = NSCountedSet(array: values)
let maxElement = countedSetOfValues.allObjects.maxElement { first, second in
return countedSetOfValues.countForObject(first) < countedSetOfValues.countForObject(second)
}
maxElement // => "A"