core data - NSExpression is always returning zero -


i have entity called rounds has basic data golf rounds. trying calculate number of rounds average score. however, every time try , calculate these values returns 0 (zero). there no errors, , no crashes.

i have following function in 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; } 

i call method view controller set values of labels number of rounds , scoring average:

-(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; } 

can please tell me why not getting correct value?

i think nsexpression overkill simple sums. this: fetch rounds normal managed objects (nsmanagedobjectresulttype) , use kvc should have aggregators need.

nsnumber *sum = [rounds valueforkeypath:@"@sum.score"]; nsnumber *avg = [rounds valueforkeypath:@"@avg.score"]; 

simple, isn't it? check out here.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -