Индекс NSFetchedResultsController за пределами границ

Я использую NSFetchedResultsController для отображения элементов в моем табличном представлении:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [[self.fetchedResultsController fetchedObjects] count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"TagCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];;
    }

 Tag *tag = [self.fetchedResultsController objectAtIndexPath:indexPath];
 cell.textLabel.text = tag.name;

    return cell;
}

Тем не менее, этот код ломается в этой строке:

Tag *tag = [self.fetchedResultsController objectAtIndexPath:indexPath];

С этим сообщением:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'

Я NSLogged[self.fetchedResultsController fetchedObjects] и я могу подтвердить, что действительно есть объекты Tag. Если я заменю вышеприведенную строку на эту, все будет работать так, как ожидается:

Tag *tag = [[self.fetchedResultsController fetchedObjects] objectAtIndex:indexPath.row];

Я NSLoggedindexPath и индексы {0, 0} (секция 0, строка 0), поэтому я знаю, что это не проблема с секцией. Я крайне запутался в том, почему это происходит, потому что теоретически эти два куска кода делают одно и то же. Любая помощь приветствуется.

Спасибо

ОБНОВЛЕНИЕ:

id section = [[[self fetchedResultsController] sections] objectAtIndex:[indexPath section]];
NSLog(@"Section %@", section); <-- returns a valid section

Этот код приводит к тому же исключению:Tag *tag = [[section objects] objectAtIndex:[indexPath row];

Если яNSLog [section objects] он возвращает пустой массив. Я не уверен почему[fetchedResultsController fetchedObjects] возвращает массив с нужными объектами, и[section objects] ничего не возвращает Значит ли это, что создаваемые мной объекты не имеют сечения? Вот код, который я использую для добавления новых объектов:

- (void)newTagWithName:(NSString *)name
{
    NSIndexPath *currentSelection = [self.tableView indexPathForSelectedRow];
    if (currentSelection != nil) {
        [self.tableView deselectRowAtIndexPath:currentSelection animated:NO];
    }    

    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    Tag *newTag = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:self.managedObjectContext];

    // Configure new tag

    newTag.name = name;

    [self saveContext];

    NSIndexPath *rowPath = [self.fetchedResultsController indexPathForObject:newTag];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:rowPath] withRowAnimation:UITableViewRowAnimationTop];
    [self.tableView selectRowAtIndexPath:rowPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

И вот мойsaveContext метод:

- (void)saveContext
{
    // Save changes

    NSError *error;
    BOOL success = [self.managedObjectContext save:&error];
    if (!success)
    {
        UIAlertView *errorAlert = [[[UIAlertView alloc] initWithTitle:@"Error encountered while saving." message:nil delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil] autorelease];
        [errorAlert show];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
}

Я что-то здесь не так делаю?

Ответы на вопрос(4)

Ваш ответ на вопрос