在这里您可以看到项目和翻译之间的关系。
我想要的是使用特定的 Translation.language 按 Translation.name 对项目进行排序。结果应该是一个有序数组,其中的项目以特定语言排序,例如英语、德语等。
谢谢
最佳答案
编辑
您需要做的就是使用排序描述符获取所有项目翻译
我正在使用我过去编写的函数:
+(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];
}];
希望有帮助 沙尼
关于ios - 使用一对多关系对 fetchRequest 进行排序(核心数据)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8104562/