Core data NSExpression总是返回零
我有一个名为Core data NSExpression总是返回零,core-data,nsmanagedobjectcontext,nsexpression,Core Data,Nsmanagedobjectcontext,Nsexpression,我有一个名为Rounds的实体,它有关于高尔夫球回合的基本数据。我试图计算回合数以及平均分数。但是,每次我尝试计算这些值时,它都返回0(零)。没有错误,也没有崩溃 我在Rounds.m中有以下功能: +(NSNumber *)aggregateOperation:(NSString *)function onAttribute:(NSString *)attributeName withPredicate:(NSPredicate *)predicate inManagedObjectConte
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;
}
有人能告诉我为什么我得不到正确的值吗?我认为
NSExpression
对于简单求和来说太过分了。我会这样做:将轮作为普通托管对象(NSManagedObjectResultType
)获取,然后使用KVC,它应该具有您需要的聚合器
NSNumber *sum = [rounds valueForKeyPath:@"@sum.score"];
NSNumber *avg = [rounds valueForKeyPath:@"@avg.score"];
很简单,不是吗?请查看。您的代码对我很有用。您确定您的实体或属性名称中没有拼写错误吗?非常好的建议,最好保持简单。谢谢你的帮助。