Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NOT IN with Realm Swift

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)
like image 507
Kalzem Avatar asked Jan 21 '16 02:01

Kalzem


Video Answer


1 Answers

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)
like image 170
LE SANG Avatar answered Oct 13 '22 07:10

LE SANG