Using Key Paths in NSPredicates

I have an NSDictionary that contains (my own) GTPerson objects. GTPerson has an NSMutableSet *parents attribute on which I use @property and @synthesize .

From my NSDictionary, I want to filter out all GTPerson objects that have no parents, i.e. where the number of parents is 0.

I am using the following code:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parents.count = 0"]; NSArray *np = [[people allValues] filteredArrayUsingPredicate:predicate]; 

When I do this, I get the following error:

[<GTPerson 0x18e300> valueForUndefinedKey:]: this class is not key value coding-compliant for the key count.

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

Why is he trying to call count on GTPerson and not on his parents attribute?

+4
source share
1 answer

The solution to your problem is to use the @count operator, as in @" parents.@count == 0" .

Reading the exception, we see that the predicate evaluation sent a -count message to the -count object. Why?

Sending -valueForKey: to the collection (in your case, the collection is an NSSet, which was the result of evaluating the parents component of the key path) sends -valueForKey: each object in the collection.

In this case, this causes -valueForKey: @"count" sent to each GTPerson instance, and GTPerson is not an encoding of key values ​​for counting.

Instead, use the @count operator to calculate the count of the collection when you want the count of the collection, not the value of the count key, for all objects in the collection.

+15
source

All Articles