CoreDataTableViewControllerのサブクラスがあります(CoreDataとTableViewsをリンクするためにスタンフォード大学の人々が行ったUITAbleViewControllerドームのサブクラス)。このクラスでは、「definition」という属性で並べ替えて、fecthを実行したいと思います。それを実行するコードは、次のとおりです。
- (void)setupFetchedResultsController{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:self.entity];
request.propertiesToFetch=[NSArray arrayWithObject:@"definition"];
request.returnsDistinctResults=YES;
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"%K != nil", @"definition"];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%K != ''", @"definition"];
NSPredicate *predicate3= [NSPredicate predicateWithFormat:@"%K contains[cd] %@", @"definition", self.seachBar.text];
NSArray *prepredicateArray;
if ([self.seachBar.text length]) {
prepredicateArray = [NSArray arrayWithObjects:predicate1, predicate2, predicate3,nil];
}else {
prepredicateArray = [NSArray arrayWithObjects:predicate1, predicate2,nil];
}
request.predicate=[NSCompoundPredicate andPredicateWithSubpredicates:prepredicateArray];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"definition" ascending:YES ]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
正しく理解できた場合は、request.returnsDistinctResults=YESを設定します。重複をフェッチしないようにする必要があります。ただし、機能せず、この属性の値の重複が表示されます。
私がそこに欠けているものはありますか?そこにいくつかの指摘をいただければ幸いです。前もって感謝します。
編集:誰かがここで同じ問題を抱えている場合、Davidの答えを適用した後、結果のfetchedResultsControllerは、要求された値のみを持つオブジェクトを持つNSDIctionaryであり、目的のみを表示するためには非常に問題ありません。セルラベルに結果を表示するためにcellForRowAtIndexPathで行ったことの1つは、次のとおりです。
前:
HNMR *hnmr = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text=hnmr.definition;
後:
cell.textLabel.text=[[self.fetchedResultsController objectAtIndexPath:indexPath] valueForKey:@"definition"];