如何使用 NSPredicate 判断一个 Int 列表是否包含一个 Int 数? [英] How to use NSPredicate for whether a List of Int contains a Int number?

查看:75
本文介绍了如何使用 NSPredicate 判断一个 Int 列表是否包含一个 Int 数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有标签属性的 Realm 模型 Person.

I got a Realm model Person who has a tag property.

let tags = List<Int>()

现在,我想执行这样的搜索

Now, I would like to perform a search like this

realm.objects(Person.self).filter(NSPredicate(format: "\(tagID) IN tags"))
// "0 IN tags"

错误:

Terminating app due to uncaught exception 'Invalid value', reason:
 'Expected object of type (null) for property 'tags' on object of type
 'Person', but received: 0'

推荐答案

如 David 的评论中所述,您不能过滤基元列表.

As stated in David's comment, you cannot filter on a list of primitives.

10.7 版添加了对过滤器/查询以及基元聚合函数的支持,因此以下信息不再完全有效.但是,这仍然是需要注意的.

Release 10.7 added support for filters/queries as well as aggregate functions on primitives so the below info is no longer completely valid. However, it's still something to be aware of.

您只能过滤包含领域对象的列表.但是,还有其他解决方案.

You can only filter on List's that contain Realm Objects. However, there are other solutions.

这里我们获取所有 Realm 对象并使用 Swift 过滤这些对象.在这种情况下,我们想要所有标签 = 7 的人.

Here we get all of the Realm objects and filter the objects using Swift. In this case we want all of the persons that have a tag = 7.

let personResults = realm.objects(PersonClass.self)
let persons = personResults.filter { $0.tags.firstIndex(of: 7) != nil }
    
for person in persons {
    print(person.name)
}

对于另一种选择,请参阅@DávidPásztor 评论中链接中的答案.

for another option, see the answer at the link in @DávidPásztor comment.

这篇关于如何使用 NSPredicate 判断一个 Int 列表是否包含一个 Int 数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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