O.Daniel
O.Daniel

Reputation: 123

CoreData one-to-many using just one Entity

When I have two entities Parent and Child(relationship between - "children", inverse - "parent") it's simple get children of concrete parent, see code below:

Parent *parent = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Child" inManagedObjectContext:context]];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];

[request setSortDescriptors:@[sort]];

[request setPredicate:[NSPredicate predicateWithFormat:@"(parent == %@)", parent]];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(@"results :%@", results);

Yes, of course, I can get children without NSFetchRequest, but in my case I have to do that in this way; Okay, and my trouble is that I have only ONE entity, for example "Parent"(relationship - "parents", inverse - "parents"); and One Parent has 3 other parents; How to get all parents concrete parent; I try to do this:

Parent *parent = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Parent" inManagedObjectContext:context]];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];

[request setSortDescriptors:@[sort]];

[request setPredicate:[NSPredicate predicateWithFormat:@"(parents == %@)", parent]];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(@"results :%@", results);

But my program program crashes: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

Upvotes: 1

Views: 147

Answers (1)

Martin R
Martin R

Reputation: 540055

Even if you have only one entity, you need to define two relationships:

  • "parent" as to-one relationship from the entity to itself, and
  • "children" as to-many relationship from the entity to itself

and make them inverse relationships of each other. Then

[NSPredicate predicateWithFormat:@"(parent == %@)", parent]

should work as expected.

Upvotes: 4

Related Questions