问题
Let me explain first cause title may be a bit confusing.
Say I have this realm objects of type Movie:
Movie1(id: 0, genre: "horror")
Movie2(id: 1, genre: "horror")
Movie3(id: 3, genre: "sci-fi")
What I need to do is get the first for every genre (in this case Movie1
and Movie3
)
I'd like to do it w/o loops using only realm
+ NSPredicate
, so the performance is better, but I'm a bit stuck there...
So far what I got is this:
Realm().objects(Movie.self).sorted(byKeyPath: id, ascending: true)
.value(forKeyPath: "@distinctUnionOfObjects.genre")
This returns me an array with ("horror", "sci-fi")
and I can't really figure what should be the next step. If I try to do a:
.filter("genre IN %@", arrayWithDistinctGenres)
it will return me all the objects.
Probably it's simple but I cannot figure how to do it.
Any help is appreciated.
回答1:
As of Realm Swift 3.1 you can do let movies = realm.objects(Movie.self).sorted(by: ["id", true]).distinct(by: ["genre"])
, which will select the first Movie
of each genre using the sort order applied before the distinct operation.
回答2:
You need to filter by one genre at a time. Something like this
let genres = realm.objects(Genres.self)
let movies = realm.objects(Movie.self).sorted(byKeyPath: id, ascending: true)
for genre in genres {
let firstInThisGenre = movies.filter({ $0.genreId == genre.id }).first
}
来源:https://stackoverflow.com/questions/48742646/filter-realm-objects-to-only-get-one-distinct-object-by-attribute