Obtaining a quantity to many relationship for master data

I have a data model with a parent and a child. A child object has many inverse relationships with its parent entity (a child can have multiple parents). I am currently trying to get the number of parents of a specific child:

Parent *doomedParent = [self.fetchedResultsController objectAtIndexPath:indexPath];

Child *child = [doomedParent valueForKey:@"child"];
int parentCount = [[child valueForKey:@"parents.@count"] intValue];

When I try to count the parents (parental relationship) from the child, I get the following error:

'Termination of the application due to the unannounced exception "NSUnknownKeyException", reason: "[valueForUndefinedKey:]: Child entity is not a key value compatible with the encoding for the key" parents. @count ". '

Any ideas what I can do wrong?

+3
source share
2 answers

You should use -valueForKeyPath:, and not -valueForKey:, that does not follow key paths ( -valueForKey:thus faster for one-time searches). This should work:

int parentCount = [[child valueForKeyPath:@"parents.@count"] intValue];
+11
source

While Barry Wark's answer is correct for using KVC, is there a reason why you are not just getting a counter .parents NSSet, for example:

NSUInteger parentCount = [child.parents count];

KVC is great, and that’s it, but if I don’t miss something, isn’t it too difficult for this situation?

+10
source

Source: https://habr.com/ru/post/1779529/


All Articles