核心数据,排序一对多子对象 [英] Core data, sorting one-to-many child objects
问题描述
所以,让我说我有一个父母的孩子商店,父母与孩子(parent.children)有一对多的关系,他们都有名字。现在,在父母的初始提取,我可以指定一个排序描述符,以按姓名顺序返回,但我如何请求孩子们的顺序?如果我做一个[parent.children allObjects],它只是给他们一个混乱,我必须排序事后,每一次。
So, lets say I have a store of parents children and the parent has a one to many relationship to children (parent.children) and they all have first names. Now, on the initial fetch for parents I can specify a sort descriptor to get them back in order of first name but how can I request the children in order? If I do a [parent.children allObjects] it just gives them back in a jumble and I'd have to sort after the fact, every time.
谢谢,
Sam
Thanks, Sam
推荐答案
Sam,
问题正确,您想要设置一个提取,返回一个特定父的子项的排序列表。为此,我将为children实体设置一个抓取,然后使用一个谓词来限制结果:
If I read your question correctly, you want to set up a fetch that returns a sorted list of the children of a specific parent. To do this, I would set up a fetch for "children" entities and then use a predicate to limit the results:
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"children" inManagedObjectContext:moc]];
[request setSortDescriptors:[NSArray initWithObject:[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(parent == %@)", parent]];
显然,您的实体和属性名称可能不同。在最后一行中,父变量应该是对您想要其子级的父级的NSManagedObject实例的引用。
Obviously, your entity and attribute names may be different. In the last line, the parent variable should be a reference to the NSManagedObject instance of the parent whose children you want.
这篇关于核心数据,排序一对多子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!