1

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] の違いはどこですか?

私はあなたが私を助けてくれることを願っています.

編集: 最も重要なことを伝えるのを忘れています: 「名前」属性の最初の文字で区切られたセクションが必要です。(音楽アプリのように)。

ニック

4

1 に答える 1

0

NSFetchedResultsControllerを初期化するときに、nilとして渡します。sectionNameKeyPath

合格nameすると、基本的に「名前ごとに1つのセクションを作成してください」と言います。を渡すときnilは、単一​​のセクションのみを作成するように指示します。

テーブルビューメソッドの実装は私には正しく見えます。

[_fetchedResultsController sections]セクション内のオブジェクトの数などを要求できるオブジェクトの配列を提供します。対照的に、[_fetchedResultsController sectionIndexTitles]これは主に、NSFetchedResultsController使用するセクションタイトルを指定できるようにするためです(つまり、セクションごとに1つの文字列を持つ配列にこれを設定します)。あなたの場合、あなたはそれを無視することができます。

于 2013-02-02T17:09:10.923 に答える