次のモデルとコードを使用して、FRC を使用して特定の Category オブジェクトの Item オブジェクトをフェッチするために正しい述語を使用しているかどうかを把握しようとしています。
カテゴリ<----->>アイテム
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Item"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"itemLabelText" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
if (self.category.items) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@",
self.category.items];
[fetchRequest setPredicate:predicate];
}
カテゴリにアイテムがない場合は、コレクション ビューのアイテム数を 0 に設定します。
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
if ((self.category.items == nil) || [self.category.items count] == 0) {
return 0;
}
id <NSFetchedResultsSectionInfo> sectionInfo =
[self.fetchedResultsController sections][section];
return [sectionInfo numberOfObjects];
}
FRC は、指定されたカテゴリ内のアイテムだけでなく、オブジェクト コンテキスト内のすべてのアイテムを返します。追加の属性を作成/参照するのではなく、Item オブジェクトを直接取得しようとしています。