【问题标题】:Order and section an array of custom objects by date按日期对一组自定义对象进行排序和分段
【发布时间】:2016-02-19 15:48:16
【问题描述】:

我有一组自定义对象,其中包含 daterevenue。该对象名为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 月、2015 年 10 月等...)划分的 UITableView

我尝试将日期排序为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;
}

【问题讨论】:

  • 您可以打印mutableSet.allObjects 以查看您收到的订单吗?
  • 因为 NSMutableSet 没有顺序。 link

标签: ios objective-c arrays sorting nsdate


【解决方案1】:

请使用NSMutableArrayNSMutableSet 不维护订单。你可以这样做。

// 游戏.h

#import <Foundation/Foundation.h>

@interface Game : NSObject

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

@end

// 你的视图控制器或一些辅助服务

NSMutableArray<Game *> *games = [[NSMutableArray alloc] init];
// add game objects to it
// sort
NSSortDescriptor *sortDescriptor = ;
[games sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE]]];

【讨论】:

  • 我能够按顺序对它们进行排序,现在我想将排序的月份和年份添加到数组中。这就是我正在努力的方向。
  • 您可以使用NSDateComponents从您的beginDate获取年份和月份
猜你喜欢
  • 2011-10-30
  • 1970-01-01
  • 2012-02-06
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 2018-05-12
相关资源
最近更新 更多