をテーブルビューコントローラに渡すだけでNSFetchedResultsController
という独自のインスタンスが作成されます。UITableView
に表示する管理対象オブジェクトを効率的に読み込み、オブジェクトグラフの変更に応答するクラスです。
Xcode 4.2の「マスター/ディテールアプリケーション」コアデータプロジェクトテンプレートは、このパターンを使用します。これは良いリファレンスと出発点です。あなたはNSFetchedResultsController
を持っていたら、それは例えば、テーブルビューのデータソースメソッドに取り込まオブジェクトを差し込むだけの問題だ
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
// Set up the fetched results controller.
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
:
ここではどのようにマスターテーブルビューコントローラいい加減にロードし、その結果コントローラを設定します
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = <#Get the cell#>;
NSManagedObject *managedObject = [<#Fetched results controller#> objectAtIndexPath:indexPath];
// Configure the cell with data from the managed object.
return cell;
}
詳細については、プロジェクトテンプレートを参照し、NSFetchedResultsController classとNSFetchedResultsControllerDelegate protocolの両方の参考資料をお読みください。 Appleのマニュアルには、完全なソースコードの例が含まれています。
ああ!これを試してみてください!ありがとうございました! – JAManfredi