Fetch Relationship Objects

百般思念 提交于 2019-12-04 08:42:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6878286/fetch-relationship-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!