I have a list of Realm objects (let's say User) and I want to retrieve all of them but "John", "Marc", "Al' Med" and so on.
I tried the following:
var namesStr = ""
for user in unwantedUsers {
namesStr += "'" + user.name + "', "
}
namesStr = String(namesStr.characters.dropLast().dropLast())
let predicate = NSPredicate(format: "NOT name IN {%@}", namesStr)
let remainingUsers = uiRealm.objects(User).filter(predicate)
I also tried with NSPredicate(format: "name NOT IN {%@}", namesStr)
but it would crash (exception raised).
And second thing, how am I suppose to escape the names in the NSPredicate. If one of the names has a ' character, it won't probably work.
EDIT
Thanks to LE SANG, here's the functional result:
var userArr: [String] = []
for user in unwantedUser {
userArr.append(user.name)
}
let predicate = NSPredicate(format: "NOT name IN %@", userArr)
let remainingUsers = uiRealm.objects(User).filter(predicate)
According to the Realm document, these ways should work
let predicate = NSPredicate(format: "NOT (name IN %@)", namesStr)
let predicate = NSPredicate(format: "!(name IN %@)", namesStr)
let predicate = NSPredicate(format: "NOT name IN %@", namesStr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With