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