【问题标题】:Sort fetchRequest with to-many relationship (Core Data)?使用一对多关系(核心数据)对 fetchRequest 进行排序?
【发布时间】:2011-11-13 00:58:09
【问题描述】:

这里可以看到Item和Translation的关系。

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

谢谢

【问题讨论】:

    标签: ios core-data nspredicate nssortdescriptor


    【解决方案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];
     }];
    

    希望对你有帮助 沙尼

    【讨论】:

    • 感谢您的快速响应,但这不起作用。我收到此错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'。这是因为翻译(对多)关系。
    • 我也忘了说我要按translations.name 排序。在你的回答中你写了 translations.language 但这应该不会有太大的不同。
    • 编辑了我的答案。我希望它现在能满足您的需求
    • 感谢您的帮助,它成功了。认为无需迭代任何翻译就可以更轻松地解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多