0

I have an array of custom objects which contain date and revenue. The object called Game.

I've sorted the array of objects using compare:

- (NSArray*)sortByDate:(NSArray*)objects
{
    NSArray *sorted = [objects sortedArrayUsingComparator:^(id firstObject, id secondObject) {
        Game *firstGameObject = (Game*)firstObject;
        Game *secondGameObject = (Game*)secondObject;
        return [(NSDate*)firstGameObject.date compare:(NSDate*)secondGameObject.date];
    }];

    return sorted;
}

I want to sort them by date and then set them into a UITableView sectioned by the month and year (April 2013, October 2015 and so on...)

I've tried to sort the dates into a MMMM YYYY format but they added in the wrong order inside the array.

- (NSArray*)getSectionsTitles:(NSArray*)objects
{
    NSMutableSet *mutableSet = [[NSMutableSet alloc] init];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [NSLocale currentLocale];
    dateFormatter.timeZone = calendar.timeZone;
    [dateFormatter setDateFormat:@"MMMM YYYY"];

    for (Game *game in objects)
    {
        NSString *sectionHeading = [dateFormatter stringFromDate:game.date];
        [mutableSet addObject:sectionHeading];
    }

    return mutableSet.allObjects;
}
ytpm
  • 4,962
  • 6
  • 56
  • 113
  • can you display a print of `mutableSet.allObjects` to see the order you get ? – tgyhlsb Feb 19 '16 at 15:59
  • 1
    Because an NSMutableSet has no order. [link](http://stackoverflow.com/questions/15686243/nsmutableset-intput-is-not-in-the-same-order-as-output) – meth Feb 19 '16 at 16:12

1 Answers1

1

Please use NSMutableArray, NSMutableSet doesn't maintain the order. You can do something like this.

// Game.h

#import <Foundation/Foundation.h>

@interface Game : NSObject

@property (nonatomic, strong) NSDate *beginDate;
@property (nonatomic, assign) NSInteger revenue;

@end

// your viewcontroller or some helperservice

NSMutableArray<Game *> *games = [[NSMutableArray alloc] init];
// add game objects to it
// sort
NSSortDescriptor *sortDescriptor = ;
[games sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE]]];
PT Vyas
  • 722
  • 9
  • 31
Puneet Arora
  • 199
  • 7
  • I was able to sort them by order, by now I want to add the months and year sorted to the array. This is what i'm struggling in. – ytpm Feb 19 '16 at 22:30
  • You can use `NSDateComponents` to get year and month from your `beginDate` – Puneet Arora Feb 20 '16 at 18:55