Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch Relationship Objects

CoreData beginner

I have a simple problem with CoreData. My model has two entities, now called A and B. Entity A has a to many relationship of B entities, which has a inverse relationship to entity A.

I'm retrieving entities A with this code:

NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"A"
                                          inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                           ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:descriptor]];

NSError *error = nil;
NSArray *items = [context executeFetchRequest:request error:&error];

if (error) /* ... */;

for (id item in items)
{
    /* ... */
}

[request release];
[descriptor release];

Now I'd like to retrieve, inside that loop, an array of all the objects B pointed by the relationship of A. How can I achieve this? Should I create another fetch request or there is a more practical way?

I've searched StackOverflow and found similar questions, but too vague sometimes.

like image 314
apgl Avatar asked Jul 29 '11 19:07

apgl


1 Answers

NSFetchRequest has an instance method on it called -setRelationshipKeyPathsForPrefetching:.

This method takes an array of key names that will be used to prefetch any objects defined in relationships with those key paths. Consider your example, updated with the new code:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSString *relationshipKeyPath = @"bObjects"; // Set this to the name of the relationship on "A" that points to the "B" objects;
NSArray *keyPaths = [NSArray arrayWithObject:relationshipKeyPath];
[request setRelationshipKeyPathsForPrefetching:keyPaths];

Now once you complete your fetch request, all of those relationship objects should be faulted in and ready to go.

like image 149
Mark Adams Avatar answered Sep 28 '22 08:09

Mark Adams