NSExpression总是返回零

时间:2013-08-24 01:38:30

标签: core-data nsmanagedobjectcontext nsexpression

我有一个名为Rounds的实体,其中包含有关高尔夫球轮的基本数据。我正在尝试计算轮次数和平均分数。但是,每次我尝试计算这些值时,它都会返回0(零)。没有错误,也没有崩溃。

我在Rounds.m:

中有以下功能
+(NSNumber *)aggregateOperation:(NSString *)function onAttribute:(NSString *)attributeName withPredicate:(NSPredicate *)predicate inManagedObjectContext:(NSManagedObjectContext *)context
{
    NSExpression *ex = [NSExpression expressionForFunction:function
                                 arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:attributeName]]];

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

    NSArray *properties = [NSArray arrayWithObject:ed];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setPropertiesToFetch:properties];
    [request setResultType:NSDictionaryResultType];

    if (predicate != nil)
        [request setPredicate:predicate];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Rounds"
                              inManagedObjectContext:context];
    [request setEntity:entity];

    NSArray *results = [context executeFetchRequest:request error:nil];
    NSDictionary *resultsDictionary = [results objectAtIndex:0];
    NSNumber *resultValue = [resultsDictionary objectForKey:@"result"];
    return resultValue;
}

然后我从我的视图控制器调用此方法来设置轮数和平均得分的标签值:

-(NSNumber*) scoringAverageCalc
{
    NSNumber *scoreAverage = [Rounds aggregateOperation:@"average:" onAttribute:@"roundScore" withPredicate:nil inManagedObjectContext:_managedObjectContext];
    return scoreAverage;
}

-(NSNumber*)countOfRounds
{
    NSNumber *roundCount = [Rounds aggregateOperation:@"count:" onAttribute:@"roundDate" withPredicate:nil inManagedObjectContext:_managedObjectContext];
    return roundCount;
}

有人可以告诉我为什么我没有得到正确的价值吗?

2 个答案:

答案 0 :(得分:2)

我认为NSExpression对于简单的总和来说是过度的。我会这样做:将你的回合作为普通的托管对象(NSManagedObjectResultType)获取,然后使用KVC,它应该只有你需要的聚合器。

NSNumber *sum = [rounds valueForKeyPath:@"@sum.score"];
NSNumber *avg = [rounds valueForKeyPath:@"@avg.score"];

简单,不是吗?请查看here

答案 1 :(得分:0)

您的代码适合我。您确定您的实体或属性名称中没有拼写错误吗?

相关问题