xcode 核心数据,一对多子对象排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2524284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:14:13  来源:igfitidea点击:

Core data, sorting one-to-many child objects

iphoneobjective-cxcodecore-data

提问by Shizam

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.

所以,假设我有一个父母孩子的商店,父母与孩子有一对多的关系(parent.children),他们都有名字。现在,在对父母的初始提取时,我可以指定一个排序描述符以按名字的顺序将它们取回,但是我如何按顺序请求孩子?如果我做一个 [parent.children allObjects] 它只会把它们弄得一团糟,我每次都必须事后排序。

Thanks, Sam

谢谢,山姆

回答by shosti

If you just want to use an NSArray, and not an NSFetchedResultsController, there's another way:

如果您只想使用 NSArray 而不是 NSFetchedResultsController,还有另一种方法:

NSSortDescriptor *alphaSort = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:alphaSort]];

回答by Tim Isganitis

Sam,

山姆,

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:

如果我正确阅读了您的问题,您希望设置一个 fetch 返回特定父级的子项的排序列表。为此,我将为“子”实体设置提取,然后使用谓词来限制结果:

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]];

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.

显然,您的实体和属性名称可能不同。在最后一行中,父变量应该是对您想要其子对象的父对象的 NSManagedObject 实例的引用。