核心数据,计数和分组

时间:2012-03-19 20:21:21

标签: objective-c ios core-data

我有一个具有2个属性的实体,一个NSDate和一个布尔值。 (这将是一个很大的“表”)

我需要计算两个日期之间布尔值的所有YES和NO值,按天分组。我怎样才能做到这一点?

The result I'm looking for is 
{
totalYes = 10,
totalNo = 5,
date = dd-mm-yyyy
},
{
totalYes = 15,
totalNo = 3,
date = dd-mm-yyyy
},

由于

1 个答案:

答案 0 :(得分:1)

您可以尝试这种方法:

1)获取所有entety,按日期排序

2)转到此数组并使用带有日期值和日期数的字典填充数组

3)然后,用noe做一个ame的事情,在那个字典数组中添加no数。

NSFetchRequest *request = [[NSFetchRequest alloc]init];
request.entity = [NSEntityDescription entityForName:@"Day" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"yesorno = %@",YES];

NSError *error = nil;
request.sortDescriptors =[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
//Here you get all the enteties with YES,sorted by date

NSArray *days = [context executeFetchRequest:request error:&error];
NSMutableArray *arrayOfDates = [NSMutableArray array];
int firstDay = [[[NSCalendar currentCalendar]components:NSDayCalendarUnit fromDate:[[days objectAtIndex:0]date]]day];
//Add the first day dictionary
[arrayOfDates addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[[days objectAtIndex:0]date],@"Day", nil];

int numberOfYes = 0;
int dayNumber = 0;
for(NSManagedObject *day in days)
{   
    if( [[[NSCalendar currentCalendar]components:NSDayCalendarUnit fromDate:[day date]]day]>firstDay)
    {   
        //save number of yeses for the previous day,because we are done with it
        [[arrayOfDates objectAtIndex:dayNumber]setValue:[NSNumber numberWithInt:numberOfYes] forKey:@"NumberOfYes"];
        numberOfYes = 1;
        dayNumber++;
        firstDay = [[[NSCalendar currentCalendar]components:NSDayCalendarUnit fromDate:[day date]]day];//date with new day
        [arrayOfDates addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[day date],@"Day", nil];//Add this day dictionary to array

    }else
         {
             numberOfYes++;
         }

}
         //And somrthing similar to No