2013-08-21 12 views
9

Ho un'entità che viene visualizzata in una vista tabella in una sola sezione. L'entità ha due attributi, workoutName e trainingLevel. Entrambi sono di tipo stringa. Il livello di allenamento è composto dai 3 tipi: 1, 2, 3. (trainingLevel = (intero 16 o tipo stringa? Quale sarebbe l'ideale?) Vorrei dividere il tavolo in tre sezioni, ciascuna sezione contenente voci per il corrispondente livello di allenamento .?iOS UITableView sezioni con fetchedResultsController confusione

come faccio a fare questo il codice attualmente sto usando è qui sotto:

- (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.workoutType.workouts.count; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = 
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
            reuseIdentifier:CellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 


    WorkoutSet *workoutSet = [self.fetchedResultsController objectAtIndexPath:indexPath]; 


    cell.textLabel.text = workoutSet.workoutName; 
    cell.detailTextLabel.text = [NSString stringWithFormat:@"(%d)", workoutSet.days.count];  
} 

-(void)fetchWorkoutSets 
{ 

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"WorkoutSet"]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"workoutType = %@", self.workoutType]; 

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"workoutName" ascending:YES]; 
    [fetchRequest setSortDescriptors:@[sortDescriptor]]; 
    [fetchRequest setPredicate:predicate]; 
    self.fetchedResultsController = [[NSFetchedResultsController alloc] 
           initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext 
           sectionNameKeyPath:nil cacheName:nil]; 

    NSError *error; 
    if (![self.fetchedResultsController performFetch:&error]) 
    { 
     NSLog(@"Fetch failed: %@", error); 
    } 
} 

Quello che sto lottando con è:

  • Come determinare il numero di righe per ogni sezione attraverso il modello di dati di base recuperando il numero di voci con il livello di addestramento 1 o 2 o 3.
  • Come riempire le righe di ogni sezione recuperando gli elementi corretti.
  • Come assegnare un titolo a ogni intestazione di sezione.
+3

Sei praticamente lì. Basta controllare la documentazione di 'NSFetchedResultsController', in particolare il parametro' sectionNameKeyPath' del programma di inizializzazione designato, che si desidera impostare come proprietà 'trainingLevel'. – Rog

+0

Si noti inoltre che il getter 'fetchedResultsController' dovrebbe eseguire il recupero, non' fetchWorkoutSet', altrimenti si avranno due chiamate diverse se è necessario assicurarsi che il set di allenamento sia stato recuperato e che sia necessario recuperare i risultati. – memmons

risposta

17

Ecco un buon tutorial sull'utilizzo fetchedResultsControllers: http://www.raywenderlich.com/999/core-data-tutorial-for-ios-how-to-use-nsfetchedresultscontroller

Creare alcune proprietà di trattenere il contesto e recupera:

@property (nonatomic,strong)NSManagedObjectContext* managedObjectContext; 
@property (nonatomic,retain)NSFetchedResultsController *fetchedResultsController; 

nella vostra proprietà fetchedResultsController, utilizzare sectionKeyNamePath per impostare i risultati recuperati nelle sezioni:

- (NSFetchedResultsController *)fetchedResultsController { 

    if (_fetchedResultsController != nil) { 
     return _fetchedResultsController; 
    } 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription 
              entityForName:@"Workouts" 
            inManagedObjectContext:managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] 
     initWithKey:@"workoutName" ascending:NO]; 
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 

    [fetchRequest setFetchBatchSize:20]; 

    NSFetchedResultsController *theFetchedResultsController = 
     [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
      managedObjectContext:managedObjectContext 
       sectionNameKeyPath:@"trainingLevel" 
         cacheName:@"Root"]; 
    self.fetchedResultsController = theFetchedResultsController; 
    _fetchedResultsController.delegate = self; 

    return _fetchedResultsController; 

} 

Il tuo popolazione iniziale del vostro fetchedResultsController può accadere nella vostra -viewDidLoad:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSError *error; 
    if (![[self fetchedResultsController] performFetch:&error]) { 
     // Update to handle the error appropriately. 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     exit(-1); // Fail 
    } 
} 

Farebbe quindi restituire il numero di sezioni e il numero di righe in sezioni come questo:

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

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

    return [sectionInfo numberOfObjects];   
} 

si può quindi ottenere il vostro gestito oggetto per la riga particolare come questa:

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

    // init the cell 
    // and whatever other setup needed 

    WorkoutSet *workoutSet = 
     [self.fetchedResultsController objectAtIndexPath:indexPath]; 

    // configure the cell from the managedObject properties 
} 
+0

Ho provato quanto sopra senza fortuna, principalmente avendo problemi verso la fine dove hai detto di usare NSManagedObject .... Non sono sicuro di come posso ottenere i miei dati attraverso quello ... Grazie – user2512523

+1

@ user2512523 Aggiornato con codice aggiuntivo a rendilo più chiaro. Gli oggetti 'WorkoutSet' sono ciò che viene restituito da' fetchedResultsController'. – memmons

+0

@ user2512523 Se questa risposta ti ha aiutato, contrassegnala come accettata in modo che la domanda non venga ancora visualizzata. – memmons

Problemi correlati