Pergunta

I am using an NSFetchedResultsController and I would like to create two sections in my table based on a date field in my entity. I don't want to section based on the individual dates, but I'd like to have one section where that date field is nil and one section where that date field is not nil.

Is there a way to use the sectionNameKeyPath to achieve this? If not, how should I go about sectioning my fetched results table based on a nil vs non-nil value?

Foi útil?

Solução

I think that the following should work:

  • Use your date field as first sort descriptor.
  • Define a transient attribute sectionIdentifier and use that as sectionNameKeyPath.
  • Define the getter function for the transient property that returns only "0" or "1". In the simplest case (without caching), it would look like this:

    - (NSString *)sectionIdentifier
    {
       if (self.date == nil)
          return @"0";
       else
          return @"1";
    }
    
  • Implement a custom titleForHeaderInSection:

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
        if ([[sectionInfo name] isEqualToString:@"0"])
            return @"Date is nil";
        else
            return @"Date is not nil";
    }
    
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top