筛选领域对象以按属性仅获取一个(不同的)对象 [英] Filter realm objects to only get one (distinct) object by attribute

查看:87
本文介绍了筛选领域对象以按属性仅获取一个(不同的)对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我解释一下原因,标题可能有些混乱.

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")

我需要做的是每种类型的第一首(在这种情况下为Movie1Movie3)

What I need to do is get the first for every genre (in this case Movie1 and Movie3)

我想只使用realm + NSPredicate进行循环,所以性能更好,但是我有点卡住了...

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") 

这将返回一个包含("horror", "sci-fi")的数组,我无法真正确定下一步应该做什么.如果我尝试执行以下操作:

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) 

它将返回所有对象.

可能很简单,但我不知道该怎么做.

Probably it's simple but I cannot figure how to do it.

感谢您的帮助.

推荐答案

从Realm Swift 3.1开始,您可以执行let movies = realm.objects(Movie.self).sorted(by: ["id", true]).distinct(by: ["genre"]),它将使用在不同操作之前应用的排序顺序来选择每种类型的前一个Movie.

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.

这篇关于筛选领域对象以按属性仅获取一个(不同的)对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆