私は2つのエンティティを持っています。クライアントとプロジェクト。クライアントには多くのプロジェクトがありますが、プロジェクトは 1 つのクライアントにしか割り当てることができません。これはデータモデルで設計されています。
- クライアント エンティティには属性clientNameと多数のプロジェクトへの関係があります
- プロジェクト エンティティには属性projectNameと 1 つのクライアントとの関係があります
クライアントがclientNameの昇順でソートされているManagedObjectContextからすべてのクライアントを取得し、そのクライアントのプロジェクトをprojectNameの昇順で取得したいと考えています。
これは私の現在のコードですが、 Client エンティティがprojectNameでソートする方法がないため、間違っていることがわかっています。
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Client" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Creating the sort descriptors array.
NSSortDescriptor *clientSort = [[NSSortDescriptor alloc] initWithKey:@"clientName" ascending:YES];
// this next row is super wrong
NSSortDescriptor *projectSort = [[NSSortDescriptor alloc] initWithKey:@"projectName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:clientSort. projectSort, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSError *error;
// Assign to NSArray of ViewController
clientArray = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
これが に割り当てられた後clientArray
、別のメソッドに移動して、プロジェクトを要求し、それらを昇順で取得したいと考えています。例:
Client *temp = (Client *)[clientArray objectAtIndex:selectedClient];
NSArray *projectsArray = [temp.projects allObjects];
Project *project = [projectsArray objectAtIndex:selectedProject];
return project.projectName;
彼らがクライアントを取得し、プロジェクトを手動でソートする実装を見ました...しかし、これは一種の高価であり、コンテキストが照会されたときにこれを行う関数があることを望んでいます。