SubEntitiesByName master data when searching for an object using the attribute

I am trying to get an entity from master data depending on an attribute called "name". Here is my code:

NSManagedObjectContext *context = [self managedObjectContext]; NSEntityDescription *vegetable = [NSEntityDescription insertNewObjectForEntityForName:@"Vegetable" inManagedObjectContext:context]; // get the vegetable using name NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", myGardenViewModel.vegetable.name]; [request setEntity:vegetable]; [request setPredicate:predicate]; NSError *error; NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:request error:&error]; 

The last line throws the following exception:

 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Vegetable subentitiesByName]: unrecognized selector sent to instance 0x6bbcdd0' 

any ideas?

+4
source share
1 answer

The problem is how you set up the entity property of your NSFetchRequest . Using insertNewObjectForEntity: you actually create a new object to insert into the database later using [managedObjectContext save:&error]; .

What you want to do is simply set the entity for your select query, and not insert a new object:

 NSEntityDescription *vegetable = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:self.managedObjectContext]; 
+7
source

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


All Articles