问题
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