Índice NSFetchedResultsController além dos limites
Estou usando um NSFetchedResultsController para exibir itens na minha exibição de tabela:
- (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;
}
No entanto, esse código quebra nesta linha:
Tag *tag = [self.fetchedResultsController objectAtIndexPath:indexPath];
Com esta mensagem:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'
Eu tenho NSLogged[self.fetchedResultsController fetchedObjects]
e posso confirmar que, de fato, existem objetos Tag. Se eu substituir essa linha acima por isso, tudo funcionará conforme o esperado:
Tag *tag = [[self.fetchedResultsController fetchedObjects] objectAtIndex:indexPath.row];
I NSLoggedindexPath
e os índices são {0, 0} (seção 0 linha 0), então eu sei que não há problema com a seção. Estou extremamente confuso sobre o motivo de isso estar acontecendo porque, teoricamente, esses dois pedaços de código fazem a mesma coisa. Qualquer ajuda é apreciada.
obrigado
ATUALIZAÇÕES:
id section = [[[self fetchedResultsController] sections] objectAtIndex:[indexPath section]];
NSLog(@"Section %@", section); <-- returns a valid section
Este código resulta na mesma exceção:Tag *tag = [[section objects] objectAtIndex:[indexPath row];
Se euNSLog
[section objects]
retorna uma matriz vazia. Não sei por que[fetchedResultsController fetchedObjects]
retorna uma matriz com os objetos certos e[section objects]
não retorna nada. Isso significa que os objetos que estou criando não têm seção? Aqui está o código que eu uso para adicionar novos objetos:
- (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];
}
E aqui está o meusaveContext
método:
- (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]);
}
}
Estou fazendo algo errado aqui?