Search code examples
iosswiftrealm

Realm Swift - Filtering results with List<object> with List<object>


I have a class called Artist, which has a list of Genres in it.

Elsewhere in the app, the user is able to select multiple genres, and a list of Artists should be filtered to show if they match one of the marked genres.

The UITableView datasource is my Results<Artist>

From what I can gather, I can't have a list of Strings, so I've made my own class RealmString which contains a string

class Artist: Object {
    let genres = List<RealmString>()
}

class RealmString: Object {
    convenience init(string: String){
        self.init()
        self.stringValue = string
    }

    dynamic var stringValue = ""
}

All of this works, and I can display the genres as expected.

When I try to filter my Results<Artist> by a List<RealmString> I'm getting the following error.

artists = unFilteredArtists.filter("genres IN %@", genreListToFilter)

*** Terminating app due to uncaught exception 'Invalid predicate', reason: 'Key paths that include an array property must use aggregate operations'

So then I tried this, but I get no results (but no crash)

artists = unFilteredArtists.filter("ANY genres IN %@", genreListToFilter)

What I'm expecting is if I have two artists

1: glitch, funk, bass

2: dub, drum, disco

And the users selects bass + disco that both artists would show.

I'm missing something, but I'm not sure what?


Solution

  • You forgot '.stringValue', try this:

    all.filter("ANY genres.stringValue IN %@", ["Pop", "Jazz"])