Search code examples
swift2realm

Swift Realm filter on relationship object


I am trying to carry out a filter on a List of Realm objects in the following way.

I have two objects Category and Company

class Category: Object {
    dynamic var name = ""
    dynamic var isActive = true
    let companies = List<Company>() 
}

class Company: Object {
    dynamic var name = ""
}

The category is sent from one Controller to another so that all the Companies in that Category can be shown

var category: Category!
var rlmCompanies: List<Company>?

So far so good, and from this I can display a list of companies. However, I am trying to add a switch bar to the top of the controller that will allow me to further filter the list of companies shown by whether they are active or not.

The code I am trying is on the lines of one of the following things I have tried

rlmCompanies = category.companies.filter("ANY isActive == true")
rlmCompanies = category.companies.filter("ANY companies.isActive == true")
rlmCompanies = category.companies.filter("companies.isActive == true")
rlmCompanies = rlmCompanies.filter("ANY companies.isActive == true")
rlmCompanies = self.rlmCompanies.filter("ANY companies.isActive == true")

All of these attempts give a similar error which is on the lines of:

No filter candidates produce the expected contextual result type List<Company>

I'm therefore running out of ideas. I can see that this is something to do with how the List has been initialised, but can't see what to do with it


Solution

  • In the end I changed the code in the following ways

    I changed the initialiser to be a Results object

    var rlmCompanies: Results<Company>?
    

    Then when I created the initial List I added a filter that returned all, and so returns a Result rather than a List

    rlmCompanies = category.companies.filter("id <> 'somethingbogus' ")
    

    I'd ideally have something like ANY rather than the id is not something bogus but can't find the syntax for that