Retrieve communication objects

Newbie CoreData p>

I have a simple problem with CoreData. My model has two entities, which are now called A and B. Entity A has many relationships B of objects, which is inversely related to object A.

I get A objects 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 would like to get inside this loop an array of all objects B, denoted by A. How can I achieve this? Should I create another fetch request, or is there a more practical way?

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

+6
source share
1 answer

NSFetchRequest has an instance method called -setRelationshipKeyPathsForPrefetching:

This method accepts an array of key names that will be used to prefetch any objects defined in relation to these 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, as soon as you fill out the selection request, all these relationship objects should be damaged and ready to go.

+10
source

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


All Articles