DaSilva DaSilva - 11 months ago 41
iOS Question

Query Realm get object witch have particularly object in a list

I think this is a simple solution, but i´m stuck with the best approach.

My Realm Database is made with the objects POI and CATEGORY. Where a POI can have one or multiple object of CATEGORY

class POI: Object {

dynamic var id:String = ""
dynamic var name:String = ""
dynamic var visited:Bool = false;

let categories = List<CATEGORY>()

override static func primaryKey() -> String?
return "id";

Later I need to show the number of POI that have a particular CATEGORY, and the number of POI that have a given CATEGORY with the boolean visited has true.

Something like this:

func getAllVisitedPointsWithCategory(idCategory:String) -> Results<POI> {


func getAllPointsWithCategory(idCategory:String) -> Results<POI>{


Any suggestion?
Thanks in advance

Answer Source

This should work:

func getAllVisitedPointsWithCategory(idCategory:String) -> [POI]  {
    let containingPOI = getAllPointsWithCategory(idCategory)

    return containingPOI.filter({ (poi) -> Bool in
        return poi.visited

func getAllPointsWithCategory(idCategory:String) -> [POI] {
    let realm = try! Realm()
    let containingPOI = realm.objects(POI).filter({ (poi) -> Bool in
        return poi.categories.contains({ (cat) -> Bool in
            return idCategory == cat.id

    return containingPOI

It's basically just querying data and filtering the result.