objective c - Perform operation on two Core Data Attributes with NSExpressions -


things max, min, , avg can calculated fine,

nsexpression *maxdate = [nsexpression expressionforkeypath:@"startdate"]; nsexpression *maxdateexpression = [nsexpression expressionforfunction:@"max:"                                                             arguments:@[maxdate]]; nsexpressiondescription *maxdateexpressiondescription = [[nsexpressiondescription alloc] init]; [maxdateexpressiondescription setname:@"maxdate"]; [maxdateexpressiondescription setexpression:maxdateexpression]; [maxdateexpressiondescription setexpressionresulttype:nsdateattributetype];    [request setpropertiestofetch:@[maxdateexpressiondescription]];   // execute fetch. nserror *error = nil;  nsarray *objects = [context executefetchrequest:request error:&error]; if (error) {     // handle error.      nslog(@"error!"); } else {     nslog(@"max date is: %@", [objects[0] objectforkey:@"maxdate"]); ] 

but, given have "item" entities, price bought , price sold attributes, how calculate total profit of item entities using nsexpressions?

thank you

the following expression description computes price difference each object:

nsexpression *price1expr = [nsexpression expressionforkeypath:@"price1"]; nsexpression *price2expr = [nsexpression expressionforkeypath:@"price2"]; nsexpression *profitexpr = [nsexpression                                     expressionforfunction:@"from:subtract:"                                     arguments:@[price2expr, price1expr]];  nsexpressiondescription *expressiondescription = [[nsexpressiondescription alloc] init]; [expressiondescription setname:@"profit"]; [expressiondescription setexpression:profitexpr]; [expressiondescription setexpressionresulttype:nsdoubleattributetype];  nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"entity"]; [request setpropertiestofetch:@[expressiondescription]]; [request setresulttype:nsdictionaryresulttype]; nsarray *profits = [context executefetchrequest:request error:&error]; nslog(@"%@", profits); 

edit: (the question edited while writing above answer.) computing sum of price differences seems not possible single fetch request, see example chained expressions perform calculations in core data. can fetch array of price differences, using above expression description, , calculate sum using key-value coding:

nsarray *profits = result of fetch request nsnumber *totalprofit = [profits valueforkeypath:@"@sum.profit"]; nslog(@"%@", totalprofit); 

Comments