2011-11-12 9 views
0

ここでアイテムと翻訳の関係を見ることができます。私はしたいものfetchRequestを多対多の関係(Core Data)でソートしますか?

enter image description here

は、特定のTranslation.languageを使用してTranslation.name商品を並べ替えることです。結果は、特定の言語でソートされた項目を持つ順序付き配列でなければなりません。英語、ドイツ語など。

Thxを

答えて

1

EDITすべてを行う必要が

私は、私が過去に書いた関数で使用していソート記述子を持つすべてのアイテムの翻訳を取得することです

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

は、それが迅速な対応のための シャニー

+0

感謝に役立ちますが、それは動作しません願っています。私はこのエラーが発生しています: 'キャッチされていない例外 'NSInvalidArgumentException'のためにアプリケーションを終了します、理由: 'to-manyキーはここで許可されていません'。それは、翻訳(多対多)関係のためです。 – MoFuRo

+0

申し訳ありませんが、私の間違いです。私は嘆きを更新します。 – shannoga

+0

私もtranslations.nameでソートしたいと言っています。あなたの答えでは、翻訳を書いています。言語ですが、これで大きな違いはありません。 – MoFuRo