views:

1109

answers:

1

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

Out of my NSDictionary, I want to filter all the GTPerson objects which don't have any parents, i.e. where the count of parents is 0.

I'm using the following code:

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

When I execute this, I receive 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 it trying to call count on GTPerson and not on its parents attribute?

+6  A: 

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

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

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

In this case that results in -valueForKey: @"count" being sent to each GTPerson instance, and GTPerson isn't key value coding compliant for count.

Instead, use the @count operator to evaluate the count of the collection when you want the count of the collection, rather than the value of the key count on all objects in the collection.

Jim Correia