ios - How to multiply two columns and sum it in CoreData? -
i have goods in document , want multiply quantity , price of every in document , sum it.
in mysql this: select sum(price * quantity) documentgoods
here code, doesn't work.
nsfetchrequest *fetch = [[nsfetchrequest alloc] init]; [fetch setentity:[nsentitydescription entityforname:self.tablename inmanagedobjectcontext:moc]]; [fetch setresulttype:nsdictionaryresulttype]; nsexpression *multiplyexpression = [nsexpression expressionforfunction:@"multiply:by:" arguments:@[[nsexpression expressionforkeypath:@"quantity"], [nsexpression expressionforkeypath:@"price"]]]; nsexpressiondescription *expressionmultiplieddescription = [[nsexpressiondescription alloc] init]; [expressionmultiplieddescription setname:@"multiplied"]; [expressionmultiplieddescription setexpression:multiplyexpression]; [expressionmultiplieddescription setexpressionresulttype:nsdecimalattributetype]; nsexpression *sumexpression = [nsexpression expressionforfunction:@"sum:" arguments:@[[nsexpression expressionforkeypath:@"multiplied"]]]; nsexpressiondescription *expressionsummarydescription = [[nsexpressiondescription alloc] init]; [expressionsummarydescription setname:@"summary"]; [expressionsummarydescription setexpression:sumexpression]; [expressionsummarydescription setexpressionresulttype:nsdecimalattributetype]; [fetch setpropertiestofetch:@[expressionsummarydescription]]; nspredicate *searchfilter = [nscompoundpredicate andpredicatewithsubpredicates:@[[nspredicate predicatewithformat:@"removed = no"]]]; [fetch setpredicate:searchfilter]; nserror *error = nil; nsarray *objects = [moc executefetchrequest:fetch error:&error]; if(objects && [objects count] > 0) return [[objects objectatindex:0] valueforkey:@"summary"]; return [[nsdecimalnumber alloc] initwithfloat:.0f];
can please me?
i faced similar scenario entity "cart" , has fields price , quantity. sum(quantity * price) cart used following code. last nslog log required total cart price
nsfetchrequest *request = [[nsfetchrequest alloc] init]; request.entity = [nsentitydescription entityforname:@"cart" inmanagedobjectcontext:self.managedobjectcontext]; request.resulttype = nsdictionaryresulttype; nsexpressiondescription *producttotaldescr = [[nsexpressiondescription alloc] init]; [producttotaldescr setname:@"producttotal"]; [producttotaldescr setexpression:[nsexpression expressionforfunction:@"multiply:by:" arguments:[nsarray arraywithobjects: [nsexpression expressionforkeypath:@"price"], [nsexpression expressionforkeypath:@"quantity"], nil]]]; [producttotaldescr setexpressionresulttype:nsinteger64attributetype]; request.propertiestofetch = [nsarray arraywithobjects:producttotaldescr, nil]; nserror *err = nil; nsarray *results = [self.managedobjectcontext executefetchrequest:request error:&err]; nslog(@"%@",[results valueforkeypath:@"producttotal"]);
Comments
Post a Comment