Search code examples
swiftcore-datanspredicatensfetchedresultscontroller

keyPath for relationship property count


I'm trying to create an NSPredicate for a fetched results controller, the controller should only observe objects that have a relationship (where it's not nil) and where the relationship's count is greater than 0.

I've seen how to do this with a string as the argument of the predicate:

[NSPredicate predicateWithFormat:@"excludedOccurrences.@count == 0"];

from: https://stackoverflow.com/a/1195519/4096655

but I am trying to get away from literal strings so I'd like to use a key path.

Example:

import UIKit
import CoreData

class Animal: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var friends: NSSet?
}

let keyPath = #keyPath(Animal.friends.count)

results in the error: Ambiguous reference to member 'count'


Solution

  • #keyPath does not know about the @count operator. But you can use it for the "Animal.friends" key path and append @count in the predicate format string:

    NSPredicate(format: "%K.@count = 0", #keyPath(Animal.friends))