0

我有一个名为的实体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;
}

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

4

2 回答 2

2

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

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

很简单,不是吗?在这里查看。

于 2013-08-24T22:44:18.070 回答
0

Your code works for me. Are you sure there are no misspellings in your entity or attribute names?

于 2013-08-26T00:28:29.130 回答