5

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'

Community
  • 1
  • 1
Fred Faust
  • 6,696
  • 4
  • 32
  • 55
  • 2
    I don't know if there is a better solution, but `NSPredicate(format: "%K.@count = 0", #keyPath(Animal.friends))` could work. – Martin R Jan 04 '17 at 15:47
  • @MartinR it is a better solution, it causes a compile time error if the property does change, thank you! – Fred Faust Jan 04 '17 at 15:52

1 Answers1

12

#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))
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382