Is it possible to have Core Data sort the “many” part of a To-Many relationship during a fetch request?

给你一囗甜甜゛ 提交于 2019-12-06 12:38:41

Why not fetch from the reverse? I assume you already know the unique id of the boss you're interested in, so you could build a predicate like this one:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"boss.bossId == %K", bossId];
NSFetchRequest *req = [[NSFetchRequest alloc] init];
[req setEntity:employeeEntity];
[req setPredicate:pred];

That should fetch out any employee with a matching bossId, you can then add a sort descriptor to that fetch request to sort alphabetically.

Alternatively you could grab the array of NSManagedObject instances that you fetch out in your current implementation, and sort them using a sort descriptor (assumes your employees name is at the property "name"):

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YESorNO];
NSArray *sorted = [entities sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

Now populate your tableview using "sorted".

Note: I'm a little confused about why you're not using an NSFetchedResultsController for this, as it would take care of sectioning for you as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!