核心数据两个日期之间的实体属性的总和

时间:2012-09-10 14:21:13

标签: ios ios5 nspredicate nsfetchrequest

我有一个实体,它有一个数量属性[NSNumber double] ...一个NSDate属性和2个布尔属性(存储为NSNumber)...有没有办法获得“amount”属性的总和,这样date属性介于2个给定日期之间,其中一个布尔属性设置为YES ...我猜测它可以在不获取所有实体的情况下完成并将它们添加到每个实体中...

 // sum of expenses this month
NSFetchRequest *fetchMonthExp = [[NSFetchRequest alloc] init];
NSEntityDescription *entityExp = [NSEntityDescription entityForName:kTransaction inManagedObjectContext:self.context];
[fetchMonthExp setEntity:entityExp];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                          initWithKey:kDate ascending:NO];
[fetchMonthExp setSortDescriptors:[NSArray arrayWithObject:sort]];

NSPredicate *predFetchEx = [NSPredicate predicateWithFormat:@"(isExpense = YES) AND (date > %@) AND (date < %@) AND (isPendingScheduledTransaction = NO) AND (isDebtRepaiment = NO) AND (isLoanRepaiment = NO) AND (isDebt = NO) AND (isLoan = NO)",[self beginingOfMonthForDate:[NSDate date]],[NSDate date]];
[fetchMonthExp setPredicate:predFetchEx];

NSExpression *ex = [NSExpression expressionForFunction:@"sum:" 
                                             arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"totalAmountInDefaultCurrency"]]];

NSExpressionDescription *ed = [[NSExpressionDescription alloc] init];
[ed setName:@"resultExpSum"];
[ed setExpression:ex];
[ed setExpressionResultType:NSDoubleAttributeType];

NSArray *properties = [NSArray arrayWithObject:ed];
[fetchMonthExp setPropertiesToFetch:properties];

NSError *error1 = nil;
NSArray *resultsEx = [self.context executeFetchRequest:fetchMonthExp error:&error1]; <- EXC_BAD_ACCESS (code = 2, address = 0x0)
if(resultsEx == nil) {
    NSLog(@"Failed to fetch exp sum: %@", [error1 localizedDescription]);
    NSArray* detailedErrors = [[error1 userInfo] objectForKey:NSDetailedErrorsKey];
    if(detailedErrors != nil && [detailedErrors count] > 0) {
        for(NSError* detailedError in detailedErrors) {
            NSLog(@"  DetailedError: %@", [detailedError userInfo]);
        }
    }
}

该错误是什么......

-[UIView count]: unrecognized selector sent to instance 0x7856150

1 个答案:

答案 0 :(得分:0)

您想要查看NSExpressionNSPredicateHere是一个过时但有用的链接,其中包含一些可帮助您入门的信息。