hafizito
hafizito

Reputation: 63

How to retrieve unique relationship of Entities in Core Data

There must be an easier way to do this. I have search and search but can't seem to find the answer I am looking for.

Let's say we have a relationship like this EntityA<-->>EntityB

If I create 2 instance of EntityA with 3 instances of Entity B for each.

In my viewcontroller that displays all EntityB for each EntityA, it displays all 6 instead of the 3 related to it.

The only way I can get it to display correctly is if I pass a pointer from one controller to another:

viewController2.entityA = viewController1.entityA;

and then retrieve the results in the following manner:

    NSMutableArray *result = [[NSMutableArray alloc] initWithArray:[entityA.entityBs allObjects]];

I was under the impression that if you initially fetch a parent entity, the subsequent fetches are based on that rather than return all.

any help would be appreciated.

Upvotes: 2

Views: 200

Answers (1)

ferostar
ferostar

Reputation: 7082

Try something like the following:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *weightEntity = [NSEntityDescription entityForName:@"EntityB" inManagedObjectContext:[[yourCoreDataManager sharedInstance] managedObjectContext]];
[fetchRequest setEntity:weightEntity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"EntityA.name LIKE %@", @"EntityAName"]];

NSError *error = nil;
NSArray *result = [[yourCoreDataManager sharedInstance] managedObjectContext] executeFetchRequest:fetchRequest error:&error];

This way, you are only requesting for only those Entities B that belongs to a given Entity A.

Upvotes: 2

Related Questions