How to group NSMutableArray by Date

Refresh

March 2019

Views

771 time

1

I have an NSMutableArray named records which contains some single records. So the structure is like:

  • Records
    • Record ("name" : "test1", "timestamp" : "2013-09-15 12:34:35 +0000")
    • Record ("name" : "test2", "timestamp" : "2013-09-14 11:21:42 +0000")
    • Record ("name" : "test3", "timestamp" : "2013-09-14 10:47:42 +0000")
    • Record ("name" : "test4", "timestamp" : "2013-09-12 17:11:42 +0000")
    • Record ("name" : "test5", "timestamp" : "2013-09-12 19:52:42 +0000")

Know I want to display them all in a UITableView. That works fine without Sections:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    [...]

    NSManagedObject *record = [self.records objectAtIndex:indexPath.row];

    cell.recordNameLabel.text = [record valueForKey:@"name"];
    return cell;
}

But now I want to separate the records in sections by the timestamp value. So my idea is to create a new NSMutableArray named sorted Records with the following structure:

  • Records

    • Day (2013-09-15)

      • Record ("name" : "test1", "timestamp" : "2013-09-15 12:34:35 +0000")
    • Day (2013-09-14)

      • Record ("name" : "test2", "timestamp" : "2013-09-14 11:21:42 +0000")
      • Record ("name" : "test3", "timestamp" : "2013-09-14 10:47:42 +0000")
    • Day (2013-09-12)

      • Record ("name" : "test4", "timestamp" : "2013-09-12 17:11:42 +0000")
      • Record ("name" : "test5", "timestamp" : "2013-09-12 19:52:42 +0000")

How can I group/separate the Records to my sorted-structure?

Thanks for any help.

2 answers

2

One of possible solutions is:

1) Create NSDate category with will have one method, for example day:

@interface NSDate(Day)
- (NSDate*) day;
@end
@implementation NSDate(Day)
- (NSDate*) day
{
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:self];
    return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
@end

2) Use NSFetchedResultsController with sectionNameKeyPath - @"timestamp.day".

0

If "Records" is a NSMutableArray of dictionary objects with a field "timestamp" of NSDate type, you may use NSSortDescriptor

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:FALSE];
[allVideos sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

*its a descending ordered array. ascending:TRUE indicate ascending order of an array!!!