Reputation: 1
I'm having some trouble figuring out how to turn ordinary swift filtering code into an NSPredicate query with Realm. I have included a simplified example of my data structure. My goal is to figure out which of the User's contacts from the device are already registered for my app.
class User: Object {
let contacts = List<Contact>()
}
class Contact: Object {
let numbers = List<String>()
}
Each User object contains a list of 'Contacts' which are all the contacts currently stored on the Users device. And each 'Contact' Object has a list of 'numbers' because each contact can have multiple phone numbers.
In regular swift code, figuring out which of the users contacts are already registered for my app looks like this:
func alreadyRegistertedUserContacts(_ contacts: Results<Contact>,
allUsers: Results<User>) -> [Contact] {
return contacts.filter { (contact) -> Bool in
return contact.numbers.contains(where: { (number) -> Bool in
return allUsers.contains(where: { (user) -> Bool in
return user.phoneNumber == number
})
})
}
}
So the question is, for efficiencies sake, how would I change this function to use NSPredicates instead?
Thanks in advance for your help!
Upvotes: 0
Views: 1570
Reputation: 18308
Realm does not currently support using properties whose types are lists of primitives in its predicates. Until that limitation is lifted, it's not possible to filter your objects using an NSPredicate
alone.
If you were willing to change your model like so:
class StringObject: Object {
@objc dynamic var string = ""
}
class Contact: Object {
let numbers = List<StringObject>()
}
class User: Object {
let contacts = List<Contact>()
}
This should allow you to perform your filtering like so:
return contacts.filter("ANY numbers.value IN %@",
allUsers.flatMap { return $0.phoneNumber })
Upvotes: 1