将核心数据过滤/排序为数组

时间:2014-05-03 03:33:41

标签: ios objective-c arrays core-data

我有一个名为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个月,其中包含归属于它的所有实体。

3 个答案:

答案 0 :(得分: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]];
}

答案 1 :(得分:1)

使用自定义对象的数组

NSArray *sorted = [arr sortedArrayUsingFunction:dateSort context:nil];

排序功能

NSComparisonResult dateSort(Class *s1, Class *s2, void *context) {
NSDate *d1 = [Utility getDateFromTheString:s1.strDate];
NSDate *d2 = [Utility getDateFromTheString:s2.strDate];
return -1*[d1 compare:d2];

}

将字符串转换为日期

 +(NSDate *)getDateFromTheString:(NSString *)strDate{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormat dateFromString:strDate];
    return date;
}

答案 2 :(得分:0)

您在寻找fetchedResultsController吗?

例如,以下代码填充fetchedResultsController以在Grouped TableViewController中使用

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Location"
                                              inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    [fetchRequest setSortDescriptors:@[
     [[NSSortDescriptor alloc] initWithKey:@"map_name" ascending:YES],
     [[NSSortDescriptor alloc] initWithKey:@"order_num" ascending:YES]
     ]];

    [fetchRequest setFetchBatchSize:20];


    // Use the sectionIdentifier property to group into sections.

    _fetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:_managedObjectContext
                                          sectionNameKeyPath:@"map_name"
                                                   cacheName:@"LocationsList"];