2

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

Christian R
  • 1,545
  • 3
  • 13
  • 17

1 Answers1

2

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.

Community
  • 1
  • 1
utahwithak
  • 6,235
  • 2
  • 40
  • 62
  • Thanks for the quick answer. Played around with it a little and i guess a similar way would be to create a NSString attribute and set the formatted date to it. That way I don't have to create a subclass. Thanks a lot for your help and for the links. – Christian R Oct 29 '11 at 16:18