Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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) { }

While this (entity.name != "Bird") may work if you only have "Cat", "Dog", and "Bird", it doesn't work if you later add more "Animals". You can also use entity.name == "Dog" && entity.name == "Cat"

It's a case of "...will you ever have any other, in your case, Animals?"

Have fun =)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top