NSFetchedResultsController titleForHeaderInSection with formatted NSDate

↘锁芯ラ 提交于 2019-12-03 08:21:26

I found a solution:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    //Returns the title for each section header. Title is the Date.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    NSArray *objects = [sectionInfo objects];
    NSManagedObject *managedObject = [objects objectAtIndex:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    NSDate *headerDate = (NSDate *)[managedObject valueForKey:@"itemDate"];
    NSString *headerTitle = [formatter stringFromDate:headerDate];
    [formatter release];
    return headerTitle;
}

Please look over this, if you know of a better way please say!

Otherwise if your stuck with a similar problem I hope this helps!

In iOS 4.0 and later, use the [NSDateFormatter localizedStringFromDate] class method and you won't have to worry about managing the NSDateFormatter instance. Otherwise this seems to be the only way to do it.

This is the Swift version of the answer:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {        
    let sectionInfo = fetchedResultsController.sections![section]
    let objects = sectionInfo.objects
    if let topRecord:NSManagedObject = objects![0] as? NSManagedObject  {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        return formatter.string(from: topRecord.value(forKey: "itemDate") as! Date)
    } else {
        return sectionInfo.indexTitle
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!