I have a data model with a Parent entity and a child entity. The child entity has a to-many inverse relationship with Parent entity (a child can have multiple parents). I am currently trying to get the number of parents a particular child has:
Parent *doomedParent = [self.fetchedResultsController objectAtIndexPath:indexPath];
Child *child = [doomedParent valueForKey:@"child"];
int parentCount = [[child valueForKey:@"parents.@count"] intValue];
When trying to get the parents (Parent relationship) count from a child I get the following error:
'Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: the entity Child is not key value coding-compliant for the key "parents.@count".'
Any ideas what I could be doing wrong?
You should be using -valueForKeyPath:
, not -valueForKey:
, which does not follow key paths (-valueForKey:
is thus faster for single key lookups). This should work:
int parentCount = [[child valueForKeyPath:@"parents.@count"] intValue];
While Barry Wark's answer is correct for using KVC, is there any reason you don't just get the count of the .parents
NSSet
, like this:
NSUInteger parentCount = [child.parents count];
KVC is great and all, but unless I'm missing something, isn't it overkill for this situation?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With