Search code examples
core-datanspredicatensfetchedresultscontroller

How can I get all elements in a join table from NSPredicate? (for NSFetchedResultsController)


Here are my 3 tables

House
-userPermissions: [Permission]

Permission
-house: House
-user: User
-permissionLevel: String

User
-housePermissions: [Permission]

I want to get all users (regardless of permission level) for a given house.

I want to use an NSFetchedResultsController (as I may have 10k users) which means I will have to use an NSPredicate.

I've tried the following predicates:

NSPredicate(format: "SELF IN %@.@user", house.userAccesses ?? [])

Crash:Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFSet 0x128f3b070> valueForUndefinedKey:]: this class is not key value coding-compliant for the key user.'

NSPredicate(format: "%@.@user", house.userAccesses ?? [])

Crash: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "%@.@user"'


Solution

  • If you want Users as your result, your fetch request will be on the User entity:

    let req = NSFetchRequest(entityName: "User")
    

    Then, your predicate can be expressed as any user who has any housePermissions on the given house:

    req.predicate = NSPredicate(format: "ANY housePermissions.house = %@", h1)