NSFetchedResultsController が機能しているセクションの取得に問題があります。「従業員」などのエンティティと、「名前」などの文字列属性があります。今、私はNSFetchedResultsControllerを使用してUITableViewにすべての従業員の名前を表示したい...問題ありません、私のコードは次のとおりです:
if (_fetchedResultsController == nil) {
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSFetchRequest *request = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:moc];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[request setEntity:entity];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:@"name" cacheName:@"root"];
NSError *error;
[_fetchedResultsController performFetch:&error];
if (error != nil) {
NSLog(@"Error: %@", error.localizedDescription);
}
}
しかし、NSFetchedResultsController はエンティティごとにセクションを作成します。したがって、200 人の従業員がいる場合、200 のセクションが作成されます。なんで?
そして、これらのメソッドを適切に実装するにはどうすればよいですか:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [[_fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[[_fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [[_fetchedResultsController objectAtIndexPath:indexPath] valueForKey:@"name"];
return cell;
}
コンセプト全体を間違って理解してもいいですか?[_fetchedResultsController セクション] と [_fetchedResultsController sectionIndexTitles] の違いはどこですか?
私はあなたが私を助けてくれることを願っています.
編集: 最も重要なことを伝えるのを忘れています: 「名前」属性の最初の文字で区切られたセクションが必要です。(音楽アプリのように)。
ニック