问题
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