开发者

How to use NSPredicate to catch child objects?

I'm new to core开发者_Python百科 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?


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


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 =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜