0

I have a question regarding Realm on iOS.

I have an object in my Realm DB that looks like this:

class MyObject: Object {
    dynamic var id: Int!
    dynamic var val: String!
}

Let say I populate my table with those data:

| id | val |
|----|-----|
| 1  | A   |
| 2  | B   |
| 3  | A   |
| 4  | B   |
| 5  | A   |
| 6  | A   |

How can query my Realm DB to return the most represented value which is A?

Thanks

Nasedo47
  • 337
  • 3
  • 13

1 Answers1

1

Realm doesn't have a native query that'll do exactly that, but you can combine Realm's KVC support with NSCountedSet to get this fairly easily:

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"
jpsim
  • 14,329
  • 6
  • 51
  • 68