gpt4 book ai didi

ios - 按日期对自定义对象数组进行排序和分段

转载 作者:行者123 更新时间:2023-11-29 01:13:20 25 4
gpt4 key购买 nike

我有一组自定义对象,其中包含日期收入。名为 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;
}

最佳答案

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

//游戏.h

#import <Foundation/Foundation.h>

@interface Game : NSObject

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

@end

//你的 View Controller 或一些辅助服务

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

关于ios - 按日期对自定义对象数组进行排序和分段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35509295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com