Índice NSFetchedResultsController más allá de los límites
Estoy usando un NSFetchedResultsController para mostrar elementos en mi vista de tabla:
- (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;
}
Sin embargo, este código se rompe en esta línea:
Tag *tag = [self.fetchedResultsController objectAtIndexPath:indexPath];
Con este mensaje:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'
He NSLogged[self.fetchedResultsController fetchedObjects]
y puedo confirmar que efectivamente hay objetos Tag. Si reemplazo esa línea anterior con esto, todo funciona como se esperaba:
Tag *tag = [[self.fetchedResultsController fetchedObjects] objectAtIndex:indexPath.row];
I NSLoggedindexPath
y los índices son {0, 0} (sección 0 fila 0), así que sé que no es un problema con la sección. Estoy extremadamente confundido en cuanto a por qué sucede esto porque, en teoría, esos dos fragmentos de código hacen lo mismo. Cualquier ayuda es apreciada.
Gracias
ACTUALIZACIONES:
id section = [[[self fetchedResultsController] sections] objectAtIndex:[indexPath section]];
NSLog(@"Section %@", section); <-- returns a valid section
Este código da como resultado la misma excepción:Tag *tag = [[section objects] objectAtIndex:[indexPath row];
Si yoNSLog
[section objects]
devuelve una matriz vacía. No estoy seguro porque[fetchedResultsController fetchedObjects]
devuelve una matriz con los objetos correctos y[section objects]
no devuelve nada ¿Significa esto que los objetos que estoy creando no tienen sección? Aquí está el código que uso para agregar nuevos 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];
}
Y aquí está misaveContext
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]);
}
}
¿Estoy haciendo algo mal aquí?