How to use NSFetchedResultsController to generate sections after dates

无人久伴 提交于 2019-12-11 03:44:26

问题


I am presenting a list of managed objects where each has a timeStamp property. I want to sort the list chronologically using the timeStamp property which i do with a NSSortDescriptor. But I also want to generate sections based on whole dates (one section for every day)

The following will give me one section based on second-differences which is too many sections:

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"timeStamp" cacheName:@"PatientDetailViewCache"];

Is there a way to generate sections from the timeStamp property with the NSFetchedResultsController that are formatted like yy-MM-dd?

Thanks for any help

Christian


回答1:


The easiest way is on your subclassed NSManagedObject create a property for a formatted date and sort using that property. There are many questions on SO with similar questions.

Setting UITableView headers from NSFetchedResultsController

A NSFetchedResultsController with date as sectionNameKeyPath

But create a class wide NSDateFormater in the awakeFromFetch: like so:

-(void)awakeFromFetch{
    dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"yy-MM-dd"];
    [super awakeFromFetch];
}

then in the accessor for that class property do something like this:

-(NSString*)myprop{
    if(myprop==nil){
        myprop = [dateFormat stringFromDate:self.OTHERDATE];
    }
    return myprop;
}

Then your fetched results controller is:

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"myprop" cacheName:@"PatientDetailViewCache"];

Then it will return the formatted date and sort based on that.



来源:https://stackoverflow.com/questions/7867162/how-to-use-nsfetchedresultscontroller-to-generate-sections-after-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!