Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the count of a to-many relationship in core data

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?

like image 423
avenged Avatar asked Nov 30 '22 17:11

avenged


2 Answers

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];
like image 100
Barry Wark Avatar answered Dec 09 '22 15:12

Barry Wark


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?

like image 29
Nick Forge Avatar answered Dec 09 '22 17:12

Nick Forge