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

标签 iphone ios objective-c core-data nsfetchrequest

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

  • 成本 (NSDecimalNumber)
  • 存款 (NSDecimalNumber)
  • 类别 (NSString)
  • 付费( bool 值)

请求应返回 3 个最昂贵的类别,但必须遵守以下规则:

  • 如果已支付 == YES,费用成本应添加到费用类别总计中
  • 如果Paid == NO && Deposit > 0,费用存款应添加到费用类别总额
  • 如果已支付 == NO,则不应将任何内容添加到费用类别总计中

使用 NSExpression,我能够计算每个类别的每个总计,但它还包括未支付的费用成本。 有没有办法做到这一点? 非常感谢!

最佳答案

例如,您可以使用 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;

并总结了cost和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);
}

关于iphone - 获取复杂请求核心数据的谓词和表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550301/

相关文章:

javascript - 如何让网站认为 PhantomJS 不是 iPhone?

iphone - XCode 运行配置文件/检查器的配置配置文件无效 - iPhone 应用程序

ios 解析 Facebook 权限未被读取

objective-c - NSViewController loadView 加载了 "(null)"nib 但没有设置 View

iphone - iOS 将输出浮点参数传递给函数

iOS 位置管理器在手机锁定约 10 分钟后停止

ios - 启动 NSManagedObjectContext 会产生 fatal error ?

ios - 如何获得 subview Controller 的父级?

iphone - iOS:Interface Builder 的困惑

iphone - NSUserDefaults 没有保存在 iOS 模拟器中?