[英]Sort fetchRequest with to-many relationship (Core Data)?
在这里,您可以查看项目与翻译之间的关系。
我想要的是使用特定的Translation.language按Translation.name对Items进行排序。 结果应为带项的有序数组,这些项以特定语言(例如英语,德语等)排序。
谢谢
编辑
您需要做的就是使用排序描述符获取所有项目翻译
我正在使用我过去编写的函数:
+(NSArray*)fetchForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate withSortDiscriptor:(NSString*)sortdDscriptorName{
NSManagedObjectContext *moc=[[[UIApplication sharedApplication] delegate]managedObjectContext];
NSEntityDescription *entityDescription;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:moc];
[request setEntity:entityDescription];
[request setPredicate:predicate];
if (sortdDscriptorName) {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:sortdDscriptorName ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
}
NSError *error = nil;
NSArray * requestArray =[moc executeFetchRequest:request error:&error];
if (requestArray == nil)
{
// Deal with error...
}
return requestArray;
}
在您的情况下,您应该以这种方式使用它:
NSString *languageName = @"German"; //or what ever
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"language == %@",languageName];
NSArray *array = [self fetchForEntity:@"Translation" withPredicate:predicate withSortDiscriptor:@"name"];
现在,您有了所有德语翻译的清单。 然后,您可以通过以下方式获得所需的所有物品:
NSMutableArray *itemsArray = [NSMutableArray array];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Translation *translation = (Translation*)obj;
Item *item = translation.item;
[itemsArray addObject:item];
}];
希望它能帮助Shani
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.