我有一个名为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;
}有人能告诉我为什么我没有得到正确的价值吗?
发布于 2013-08-24 22:44:18
我认为NSExpression对于简单的总和来说太过分了。我会这样做:把您的循环作为普通托管对象(NSManagedObjectResultType),然后使用KVC,它应该有您需要的聚合器。
NSNumber *sum = [rounds valueForKeyPath:@"@sum.score"];
NSNumber *avg = [rounds valueForKeyPath:@"@avg.score"];很简单,不是吗?看看这里。
发布于 2013-08-26 00:28:29
你的密码对我有用。您确定您的实体或属性名称中没有拼写错误吗?
https://stackoverflow.com/questions/18414084
复制相似问题