Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 312
Fred Faust Avatar asked Jan 04 '17 15:01

Fred Faust


1 Answers

#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))
like image 140
Martin R Avatar answered Sep 20 '22 23:09

Martin R