NSFetchRequest master data for a specific relationship?

I’m moving on to the existing data model that was previously stored in XML for Core Data, so I try to learn the ropes as best as possible. Core Data, obviously, is one of those technologies that aren’t going anywhere in the near future, so I could also “learn it right”.

Take, for example, a Core Data model with two objects:

  • Person
  • Food

A person has 2 one-to-many relationships with Food :

  • favoriteFoods (1-to-many)
  • hatedFoods (1-to-many)

(Both human and food are subclasses of NSManagedObject.)

In the previous Person data model, two NSArray instance variables were NSArray . If I wanted my favorite dishes, I could call:

 Person *fred = [[Person alloc] init]; NSArray *fredsFavorites = fred.favoriteFoods; 

Easy compression.

I am reading the documentation for Core Data, and I cannot find the right way to get this NSArray based on NSFetchRequest , because I cannot determine with what relation I want to get the objects.

 NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Food" inManagedObjectContext:[fred managedObjectContext]]]; [request setIncludesSubentities:NO]; NSArray *fredsFavoriteAndHatedFoods = [[fred managedObjectContext] executeFetchRequest:request error:nil]; 

This returns all Products items stored in both favoriteFoods and hatedFoods . How can I separate them? Of course, there is a simple explanation, but I do not understand this concept well enough to explain it in the Core Data jargon, so my Google searches are fruitless.

+4
source share
1 answer

The easiest way to get this is to simply access NSSet directly:

 NSArray *fredsFavorites = [fred.favoriteFoods allObjects]; 

(I showed how to get NSArray from the resulting NSSet ).

Alternatively, if you set up the inverse relationship (what you need), you can use the select query as follows:

 NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Food" inManagedObjectContext:[fred managedObjectContext]]]; [request setPredicate:[NSPredicate predicateWithFormat:@"ANY personsWithThisAsFavorite == %@", fred]]; NSArray *fredsFavoriteFoods = [[fred managedObjectContext] executeFetchRequest:request error:nil]; 

This suggests that personsWithThisAsFavorite is an inverse relationship to favoriteFoods . If I am not reading your example incorrectly, favoriteFoods Foods should really be a many-to-many relationship, as a person can have several favorite dishes, and food can have several people with this food as a favorite.

(Note: I have not tested this, so NSPredicate may not be 100% correct)

+8
source

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


All Articles