使用CoreData执行乘法(聚合):如何?

Lor*_*o B 4 core-data nsfetchrequest nsmanagedobject nsmanagedobjectcontext ios

Jeff Lamarche的精彩教程之后,我正在尝试聚合特定子类的数据NSManagedObject.

这就是场景.我创建了一个名为Product扩展NSManagedObject类的类.Productclass有三个属性,如下所示:

@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSNumber* quantity;
@property (nonatomic, retain) NSNumber* price;
Run Code Online (Sandbox Code Playgroud)

我还创建了一个名为的类别,Product+Aggregate我执行总和聚合.特别是,按照Jeff教程,我管理了数量属性的总和.

+(NSNumber *)aggregateOperation:(NSString *)function onAttribute:(NSString *)attributeName withPredicate:(NSPredicate *)predicate inManagedObjectContext:(NSManagedObjectContext *)context
{
    NSString* className = NSStringFromClass([self class]);

    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];
    [ed release];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setPropertiesToFetch:properties];
    [request setResultType:NSDictionaryResultType];

    if (predicate != nil)
        [request setPredicate:predicate];

    NSEntityDescription *entity = [NSEntityDescription entityForName:className
        inManagedObjectContext:context];
    [request setEntity:entity];

    NSArray *results = [context executeFetchRequest:request error:nil];
    NSDictionary *resultsDictionary = [results objectAtIndex:0];
    NSNumber *resultValue = [resultsDictionary objectForKey:@"result"];

    return resultValue;
}
Run Code Online (Sandbox Code Playgroud)

此类方法从以下特定方法调用UIViewController:

NSNumber *totalQuantity = [Product aggregateOperation:@"sum:" onAttribute:@"quantity" withPredicate:nil inManagedObjectContext:self.context];
Run Code Online (Sandbox Code Playgroud)

代码效果很好.事实上,如果我说3产品

NAME         QUANTITY      PRICE
PRODUCT 1    2             23.00 
PRODUCT 2    4             12.00
PRODUCT 3    1             2.00
Run Code Online (Sandbox Code Playgroud)

aggregateOperation方法按预期返回7.

现在我还有一步.修改该方法,我需要返回产品订单的总成本.换句话说,我需要为每个产品计算QUANTITY*PRICE值,最后返回TOTAL.

你能以正确的方式向我推荐吗?先感谢您.

编辑这是我在Cyber​​fox建议后使用的新代码,但遗憾的是它不起作用.

NSString* className = NSStringFromClass([self class]);

NSArray *quantityPrice = [NSArray arrayWithObjects: [NSExpression expressionForKeyPath:@"quantity"], [NSExpression expressionForKeyPath:@"price"], nil];

NSArray *multiplyExpression = [NSArray arrayWithObject:[NSExpression expressionForFunction:@"multiply:by:" arguments:quantityPrice]];

NSExpression *ex = [NSExpression expressionForFunction:function arguments:multiplyExpression];

NSExpressionDescription *ed = [[NSExpressionDescription alloc] init];
[ed setName:@"result"];
[ed setExpression:ex];
[ed setExpressionResultType:NSInteger64AttributeType];

// same as before
Run Code Online (Sandbox Code Playgroud)

Lor*_*o B 5

对于那些感兴趣的人,我找到了上述问题的解决方案.

这是代码:

static NSString* exprName1 = @"val1";
static NSString* exprName2 = @"val2";

NSString *className = NSStringFromClass([self class]); 

NSExpression *quantityPathExpression = [NSExpression expressionForKeyPath:firstAttribute]; //e.g. quantity    
NSExpression *unitaryPricePathExpression = [NSExpression expressionForKeyPath:secondAttribute]; //e.g. price

NSExpressionDescription *quantityED = [[NSExpressionDescription alloc] init];
[quantityED setName:exprName1];
[quantityED setExpression:quantityPathExpression];
[quantityED setExpressionResultType:NSDictionaryResultType];    

NSExpressionDescription *unitaryPriceED = [[NSExpressionDescription alloc] init];
[unitaryPriceED setName:exprName2];
[unitaryPriceED setExpression:unitaryPricePathExpression];
[unitaryPriceED setExpressionResultType:NSDictionaryResultType];

NSArray *properties = [NSArray arrayWithObjects:quantityED, unitaryPriceED, nil];
[quantityED release];
[unitaryPriceED release];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setPropertiesToFetch:properties];
[request setResultType:NSDictionaryResultType];

if (predicate != nil)
   [request setPredicate:predicate];

NSEntityDescription *entity = [NSEntityDescription entityForName:className inManagedObjectContext:context];
[request setEntity:entity];

NSError* error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];

if(error != nil)
{
   NSLog(@"An error occurred: %@", [error localizedDescription]);
   abort();
}

float total = 0;
for (NSDictionary *resultDict in results) 
{
   NSNumber* quantityNumber = [resultDict valueForKey:exprName1];
   NSNumber* unitaryPriceNumber = [resultDict valueForKey:exprName2];

   int moltVal = [quantityNumber intValue]*[unitaryPriceNumber intValue];

   total += moltVal;
}    

return [NSNumber numberWithInt:total];
Run Code Online (Sandbox Code Playgroud)

PS使用它创建一个Class方法,该方法返回一个NSNumber并接受托管上下文和2个属性(NSString)的参数,以便执行数据检索.

希望能帮助到你!