Custom Core Data SectionNameKeyPath

前端 未结 2 985
执笔经年
执笔经年 2020-12-14 09:20

I am new at core data and am trying to figure out how to create a custom sectionNameKeyPath in my NSFetchedResultsController. I have a managed obje

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 10:00

    The following should work: Implement the periodYear method (which will be used as "section name key path") in a class extension of your managed object subclass:

    @interface Event (AdditionalMethods)
    - (NSString *)periodYear;
    @end
    
    @implementation Event (AdditionalMethods)
    - (NSString *)periodYear {
        return [self.acctPeriod substringToIndex:4];
    }
    @end
    

    Make sure that acctPeriod is used as the first (or only) sort descriptor for the fetch request:

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"acctPeriod" ascending:YES];
    NSArray *sortDescriptors = @[sortDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];
    

    Use periodYear as sectionNameKeyPath for the fetched results controller:

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

    And finally add the default titleForHeaderInSection method:

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

    Alternatively, you can define periodYear as transient attribute of the managed object. It will also not be stored in the database in that case, but can be implemented in a way that the value is calculated on demand and cached.

    The DateSectionTitles sample project from the Apple Developer Library demonstrates how this works.

提交回复
热议问题