2014年4月24日 星期四

如何在CoreData中做SUM運算

//節錄自http://stackoverflow.com/questions/8680975/iphone-core-data-how-to-get-sum-of-values-from-db
There are two ways to solve this problem:
first - get your data to NSSet or NSArray and use @sum operator:
//assume that `pens` are NSArray of Pen
NSNumber *countSum=[pens valueForKeyPath:@"@sum.count"];
second is using specific fetch for specific value with added NSExpressionDescription with a sum. This way is harder but better for larger db's


//以下為使用magicrecords
NSNumber *countSum = [RecordEntity MR_aggregateOperation:@"sum:" onAttribute:@"steps" withPredicate:nil];

NSLog(@"算總和 : %@",countSum);

沒有留言:

張貼留言