按日期排序并剖析一组自定义对象

按日期排序并剖析一组自定义对象

问题描述:

我有一组自定义对象,其中包含日期收入。这个对象叫做Game按日期排序并剖析一组自定义对象

我排序的对象使用数组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; 
} 

我想按日期对它们进行排序,然后将它们设置成月份和年份(2013年4月截取的UITableView,2015年10月等上...)

我试图将日期排序为MMMM YYYY格式,但它们在数组内部以错误的顺序添加。

- (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; 
} 
+0

可以显示'mutableSet.allObjects'的打印,看看你的命令得到什么? – tgyhlsb

+1

因为NSMutableSet没有顺序。 [链接](http://stackoverflow.com/questions/15686243/nsmutableset-intput-is-not-in-the-same-order-as-output) – meth

请使用NSMutableArrayNSMutableSet不维护秩序。你可以做这样的事情。

// Game.h

#import <Foundation/Foundation.h> 

@interface Game : NSObject 

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

@end 

//你的ViewController或一些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]]]; 
+0

我能够按顺序排序他们,现在我想添加排序到数组的月份和年份。这就是我正在努力的。 –

+0

你可以使用'NSDateComponents'从你的'beginDate'中获得年份和月份 –