简体   繁体   中英

Split nsarray into sections by NSDate

I have an NSArray that is extracted from core data. The entities in the array have a date attribute (of type NSDate ofcourse). What I want to do is this:

  • The array needs to be displayed in a table view,
  • the sections, and their titles are months , of the objects in the array

For example if I have 3 objects (april 1, april 3 & july 7) there should be 2 sections: - april 2012(2 obj) - july 2012 (1 obj)).

How do I split the array like this?

Try using a NSFetchedResultsController and a custom sectionNameKeyPath which should be a method in your NSManagedObject subclass.

The fetchedResultsController can be set up as following:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MyObject"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
request.sortDescriptors = @[sortDescriptor];
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:@"monthAsString" cacheName:nil];

You need to implement the monthAsString method in your managedObject subclass. Allocate the NSDateFormatter only once, because it won't perform well if you allocate a new instance for every call.

 - (NSString *)monthAsString {
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"MMMM yyyy";
    });

    NSString *dateString = [formatter stringFromDate:self.date];
    return dateString;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM