【发布时间】:2012-01-24 10:25:30
【问题描述】:
在a fantastic tutorial by Jeff Lamarche 之后,我正在尝试为NSManagedObject 的特定子类聚合数据。
这就是场景。我创建了一个名为 Product 的类,它扩展了 NSManagedObject 类。 Product 类具有如下三个属性:
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSNumber* quantity;
@property (nonatomic, retain) NSNumber* price;
我还创建了一个名为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;
}
这个类方法被一个特定的UIViewController调用如下:
NSNumber *totalQuantity = [Product aggregateOperation:@"sum:" onAttribute:@"quantity" withPredicate:nil inManagedObjectContext:self.context];
代码运行良好。事实上,如果我说 3 个产品
NAME QUANTITY PRICE
PRODUCT 1 2 23.00
PRODUCT 2 4 12.00
PRODUCT 3 1 2.00
aggregateOperation 方法按预期返回 7。
现在我会多走一步。修改该方法,我需要返回产品订单的总成本。换句话说,我需要计算每个产品的 QUANTITY*PRICE 值,最后返回 TOTAL。
你能建议我正确的方法吗?提前谢谢你。
编辑这是我在 Cyberfox 建议后使用的新代码,但不幸的是它不起作用。
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
【问题讨论】:
标签: ios core-data nsmanagedobject nsmanagedobjectcontext nsfetchrequest