我有一个名为Expense的实体的核心数据模型。它包含一个名为time的属性,用于存储NSDate。

将所有这些费用分类到按月分类的单个NSMutableArray中的有效方法是什么?

例如,如果有以下日期的五项费用:

1 1/6/2014

2 2/4/2014

3 5/2/2014

4 6/5/2014

5 9/4/2014

应该返回一个NSMutableArray,其中包含一堆数组。每个数组代表1个月,其中包含所有归因于它的实体。

最佳答案

例:

// Get expenses from Core Data
NSArray *expensesToCategorize = ...;

// Create calendar
static NSCalendar *gregorian = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
});

// Set time zone of calendar
[gregorian setTimeZone:[NSTimeZone defaultTimeZone]];

// Group expenses by month
NSMutableDictionary *expensesByMonth = [[NSMutableDictionary alloc] init];
for (Expense *expense in expensesToCategorize) {
    NSDate *date = expense.time;

    NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:date];
    [components setDay:1];

    NSDate *firstDayOfMonth = [gregorian dateFromComponents:components];

    NSMutableArray *expensesThisMonth = expensesByMonth[firstDayOfMonth];
    if (!expensesThisMonth) {
        expensesThisMonth = [[NSMutableArray alloc] init];
        expensesByMonth[firstDayOfMonth] = expensesThisMonth;
    }

    [expensesThisMonth addObject:expense];
}

// Transform into desired data structure
NSArray *sortedMonthDates = [[expensesByMonth allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *categorizedExpenses = [expensesByMonth objectsForKeys:sortedMonthDates notFoundMarker:[NSNull null]];

// Sort expenses within each month by date
for (NSMutableArray *expensesThisMonth in categorizedExpenses) {
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES];
    [expensesThisMonth sortUsingDescriptors:@[sortDescriptor]];
}

关于ios - 将核心数据过滤/排序到阵列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23439940/

10-12 16:39