objective-c - 核心数据、计数和分组依据

标签 objective-c ios core-data

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

我需要计算两个日期之间 bool 值的所有"is"和“否”值,并按天分组。我怎样才能做到这一点?

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

等等

谢谢

最佳答案

您可以尝试这种方法:

1)获取所有带YES的实体,按日期排序

2)遍历这个数组并用带有日期值和是的数量的字典填充数组

3)然后,对 noe 做同样的事情,将 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 

关于objective-c - 核心数据、计数和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777337/

相关文章:

ios - Storyboard编辑器中的 "First Responder"和 "Exit"框的用途是什么?

objective-c - 如何枚举 CGPoints 的 nsmutablearray?

iphone - 使用不同的对象类型发布单个通知

ios - 尝试实现 iAd 删除但得到 "AnyObject is not convertible to..."

ios - 我什么时候可以使用带有通用链接的 SFSafariViewController、WKWebView 或 UIWebView?

ios - 如何在导航栏中创建后退按钮

ios - 无法创建 NSManagedObject 子类

iphone - 核心数据 : Keypath "objectID" not found in entity

objective-c - 使用 NSInferMappingModelAutomaticallyOption 更改核心数据中的属性类型

iphone - 从异步回调更新 UI 组件 (dispatch_queue)