2011-12-05 18 views
6

Así que he implementado con éxito los datos centrales para recuperar objetos de un servidor, guardarlos y mostrarlos en una UITableView. Sin embargo, ahora, deseo dividirlos en secciones separadas. Lo busqué hace unos días, y NSFetchedResultsController parece confundirme, aunque funciona la forma en que lo estoy usando. Tengo una clave en mi entidad llamada "articleSection" que se establece cuando el elemento se agrega a Core Data con elementos como "Top" "Sports" "Life". ¿Cómo voy a dividirlos en secciones separadas en mi UITableView? He leído sobre el uso de múltiples NSFetchedResultsControllers, pero estoy tan frustrado como puede ser con esto.iPhone - dividiendo los datos principales en secciones con NSFetchResultsController

Cualquier sugerencia o ayuda sería muy apreciada.

+0

Véase mi respuesta en este hilo http://stackoverflow.com/questions/8037588/sectionindextitlesfortableview-keys-are-off/8037745#8037745. Espero que esta ayuda. – iamsult

Respuesta

17

El documentation for NSFetchedResultsController tiene un código de muestra que funciona perfectamente.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return [[self.fetchedResultsController sections] count]; 
} 

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    return [sectionInfo numberOfObjects]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = /* get the cell */; 
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    // Configure the cell with data from the managed object. 
    return cell; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    return [sectionInfo name]; 
} 

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 
    return [self.fetchedResultsController sectionIndexTitles]; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 
    return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index]; 
} 

Establecer los sortDescriptors de la solicitud de búsqueda para que los resultados se ordenan por articleSection.
Establezca la sección KeyPath en "articleSection" para que NSFetchedResultsController cree las secciones por usted. Algo como esto:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
request.entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];; 
request.fetchBatchSize = 20; 
// sort by "articleSection" 
NSSortDescriptor *sortDescriptorCategory = [NSSortDescriptor sortDescriptorWithKey:@"articleSection" ascending:YES]; 
request.sortDescriptors = [NSArray arrayWithObjects:sortDescriptorCategory, nil];; 

// create nsfrc with "articleSection" as sectionNameKeyPath 
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"articleSection" cacheName:@"MyFRCCache"]; 
frc.delegate = self; 
NSError *error = nil; 
if (![frc performFetch:&error]) { 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 
self.fetchedResultsController = frc; 
+0

¿Cómo hago esto si no quiero usar NSFetchedResultsController? – acecapades

Cuestiones relacionadas