使用to-many关系(核心数据)对fetchRequest进行排序?

时间:2011-11-12 12:56:42

标签: ios core-data nspredicate nssortdescriptor

在这里,您可以看到项目和翻译之间的关系。

enter image description here

我想要的是使用特定的Translation.language按Translation.name对项目进行排序。结果应该是一个有序数组,其中Items以特定语言排序,例如英语,德语等等。

THX

1 个答案:

答案 0 :(得分:1)

修改

您需要做的就是使用排序描述符

获取所有项目翻译

我正在使用我过去写过的函数:

 +(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];
 }];

希望它有所帮助 沙尼