我有一个名为的实体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;
}
有人可以告诉我为什么我没有得到正确的价值吗?