用于获取复杂请求核心数据的谓词和表达式

时间:2013-08-31 16:32:31

标签: iphone ios objective-c core-data nsfetchrequest

我必须制作复杂的核心数据获取请求,但我不知道是否可以制作。 这是我的场景:只有一个具有这些属性的实体(费用):

  • 费用(NSDecimalNumber)
  • 存款(NSDecimalNumber)
  • 类别(NSString)
  • 付费(布尔值)

请求应该返回3个最昂贵的类别,但这些是必须遵守的规则:

  • 如果已付款==是,则应将费用成本添加到费用类别总计
  • 如果付费== NO&&存款> 0 ,费用存款应添加到费用类别总计
  • 如果付费==否,则不应向费用类别总计添加任何内容

使用NSExpression,我可以计算每个类别的总计,但也包括未支付的费用。 有没有办法实现这个目标? 非常感谢你!

1 个答案:

答案 0 :(得分:1)

例如,您可以使用NSFetchRequest

// Build the fetch request
NSString *entityName = NSStringFromClass([Expense class]);
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;

仅过滤相关费用:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(paid == YES) OR ((paid == NO) AND (deposit > 0))"];
request.predicate = predicate;

并总结成本和depost属性:

NSExpressionDescription *(^makeExpressionDescription)(NSString *, NSString *) = ^(NSString *keyPath, NSString *name)
{
    // Create an expression for the key path.
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:keyPath];

    // Create an expression to represent the function you want to apply
    NSExpression *totalExpression = [NSExpression expressionForFunction: @"sum:" arguments: @[keyPathExpression]];

    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];

    // The name is the key that will be used in the dictionary for the return value
    expressionDescription.name = name;
    expressionDescription.expression = totalExpression;
    expressionDescription.expressionResultType = NSDecimalAttributeType;

    return expressionDescription;
};

NSExpressionDescription *totalCostDescription = makeExpressionDescription(@"cost", @"totalCost");
NSExpressionDescription *totalDepositDescription = makeExpressionDescription(@"deposit", @"totalDeposit");

// Specify that the request should return dictionaries.
request.resultType = NSDictionaryResultType;

request.propertiesToFetch = @[categoryDescription,
                              paidDescription,
                              totalCostDescription,
                              totalDepositDescription];

按类别和付费状态对结果进行分组:

// Get 'category' and 'paid' attribute descriptions
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
                                              inManagedObjectContext:context];
NSDictionary *attributes = [entity attributesByName];
NSAttributeDescription *categoryDescription = attributes[@"category"];
NSAttributeDescription *paidDescription = attributes[@"paid"];

// Group by 'category' and 'paid' attributes
request.propertiesToGroupBy = @[categoryDescription, paidDescription];

您将获得有偿和未支付的费用总结

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

你需要做的就是组合(和排序)然后:

if (results) {
    NSMutableDictionary *combined = [NSMutableDictionary dictionary];

    for (NSDictionary *result in results) {
        NSString *category = result[@"category"];

        BOOL paid = [result[@"paid"] boolValue];

        NSDecimalNumber *total = result[paid ? @"totalCost" : @"totalDeposit"];

        NSDecimalNumber *sum = combined[category];

        if (sum) {
            total = [total decimalNumberByAdding:sum];
        }

        combined[category] = total;
    }

    NSArray *sortedCategories = [combined keysSortedByValueUsingSelector:@selector(compare:)];

    [sortedCategories enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Category %@: %@", obj, combined[obj]);
    }];
}
else {
    NSLog(@"Error: %@", error);
}