Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSPredicate to catch child objects?

I'm new to core data and try to get all children objects of various types with one query. Say there's an "Animal" type as parent and "Cat", "Dog" and "Bird" as children. I'd like to get both cats and dogs, but not Birds in single query returned as Animal objects. Is it possible?

like image 402
cocoapriest Avatar asked Mar 11 '10 00:03

cocoapriest


2 Answers

Managed objects have an entity property, so you should be able to combine Kevin Sylvestre's solution with a predicate of entity.name != "Bird".

like image 61
Peter Hosey Avatar answered Nov 15 '22 10:11

Peter Hosey


Yes, it is possible:

// Load delegate from application and context from delegate.
SampleAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = delegate.managedObjectContext;

// Create new request.
NSFetchRequest *request = [[NSFetchRequest alloc] init];

// Create entity description using delegate object context.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Animal" inManagedObjectContext:context];

// Set entity for request.
[request setEntity:entity];
[request setIncludesSubentities:YES];

// Load array of documents.
NSError *error;
NSArray *animals = [context executeFetchRequest:request error:&error];

// Release request.
[request release];

// Access array.
for (id animal in animals) { }
like image 31
Kevin Sylvestre Avatar answered Nov 15 '22 10:11

Kevin Sylvestre