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?
+3
A:
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) { }
Kevin Sylvestre
2010-03-11 00:48:29
thanks for quick response. I'm sorry, I forgot to mention the most important thing: there's a one more child (say "Bird"). What I need is, to get both Cats and Dogs, but NOT Birds. I've edited the main question
Konstantin
2010-03-11 01:01:09
+4
A:
Managed objects have an entity
property, so you should be able to combine Kevin Sylvestre's solution with a predicate of entity.name != "Bird"
.
Peter Hosey
2010-03-12 23:42:16
It's an informal property, insofar as you can use KVC to access it (since there is a method there), as opposed to a formal (`@property`) property.
Peter Hosey
2010-03-13 17:18:43
A:
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 =)
RoLYroLLs
2010-03-15 23:31:48