简体   繁体   中英

Sort fetchRequest with to-many relationship (Core Data)?

Here you can the see the relationship between Item and Translation.

在此处输入图片说明

What I want to is to sort Items by Translation.name using a specific Translation.language. The result should be an ordered array with Items that is sorted in a specific language, eg English, German an so on.

Thx

EDIT

All you need to do is to fetch all the item translations with a sort descriptor

I am using a function I wrote in the past:

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

   }

In your case you should use call it this way:

 NSString *languageName = @"German"; //or what ever
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"language ==   %@",languageName];

 NSArray *array = [self fetchForEntity:@"Translation" withPredicate:predicate withSortDiscriptor:@"name"];

Now you have a list of all the translations in the German language. Then you can get all the items you need with:

  NSMutableArray *itemsArray = [NSMutableArray array];
 [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
   Translation *translation = (Translation*)obj;
   Item *item = translation.item;
  [itemsArray addObject:item];
 }];

Hope it helps Shani

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM