user2715505
user2715505

Reputation: 43

How to group NSMutableArray by Date

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

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:

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

Thanks for any help.

Upvotes: 1

Views: 919

Answers (2)

Sk Borhan Uddin
Sk Borhan Uddin

Reputation: 813

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!!!

Upvotes: 0

Sviatoslav Yakymiv
Sviatoslav Yakymiv

Reputation: 7935

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".

Upvotes: 2

Related Questions