sectionIdentifier for Custom Section Titles group by month or year only

时间:2015-07-28 23:02:36

标签: objective-c

I wonder if anyone could help me. I am trying to group the date records by month or year only and not by day. I appreciate your help.

`(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {

 id theSection = [[self.fetchedResultsController sections] objectAtIndex:section];

/* Section information derives from an event's sectionIdentifier, which is a string representing the number (year * 1000) + month. To display the section title, convert the year and month components to a string representation. */

     static NSDateFormatter *formatter = nil;

     if (!formatter) { formatter = [[NSDateFormatter alloc] init];  [formatter setCalendar:[NSCalendar currentCalendar]];

    NSString *formatTemplate = [NSDateFormatter dateFormatFromTemplate:@"MMM YYYY" options:0 locale:[NSLocale currentLocale]];
    [formatter setDateFormat:formatTemplate];
    }

     NSInteger numericSection = [[theSection name] integerValue];
    NSInteger year = numericSection / 10000;
    NSInteger month = (numericSection - (year * 10000))/100;
   NSInteger day = (numericSection - (year * 10000 + month * 100));


    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.year = year;
    dateComponents.month = month;
    dateComponents.day = day;
    NSDate *date = [[NSCalendar currentCalendar]           dateFromComponents:dateComponents];

    NSString *titleString = [formatter stringFromDate:date];

    return titleString;
    }`

1 个答案:

答案 0 :(得分:0)

您需要将自定义节标题实现为NSManagedObject子类中的属性(如果您自动生成NSManagedObject类,则在类别中)。这个stackoverflow answer就是你要找的。