How to use NSPredicate for whether a List of Int contains a Int number?

↘锁芯ラ 提交于 2021-02-17 03:56:50

问题


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"

Error:

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'

回答1:


As stated in David's comment, you cannot filter on a list of primitives. You can only filter on List's that contain Realm Objects. However, there are other solutions.

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

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



来源:https://stackoverflow.com/questions/57518571/how-to-use-nspredicate-for-whether-a-list-of-int-contains-a-int-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!