ios - 如何获取在 CoreData 中获取平均值的实体属性

标签 ios objective-c cocoa-touch cocoa core-data

我已经从我的 CoreData EntityAvergedGroupedBy date 结果中获取了一些值。查询效果很好。现在...我想知道这些结果的来源日期。显示的输出来自原始结果。我怎样才能让我的查询也吐出从中获取这些平均值的日期/GroupBy值(假设我的GroupBy条件是日期)来自

输出

(
        {
        averageWeight = 36;
    },
        {
        averageWeight = 22;
    }
)

代码:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ExerciseData" inManagedObjectContext:context];
    [request setEntity:entity];

    // Specify that the request should return dictionaries.
    [request setResultType:NSDictionaryResultType];

    // Create an expression for the key path.
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"weight"];

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

    // Create an expression description using the minExpression and returning a date.
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];

    // The name is the key that will be used in the dictionary for the return value.
    [expressionDescription setName:@"averageWeight"];
    [expressionDescription setExpression:expression];
    [expressionDescription setExpressionResultType:NSInteger32AttributeType]; // For example, NSDateAttributeType

    // Set the request's properties to fetch just the property represented by the expressions.
    [request setPropertiesToFetch:@[expressionDescription]];
    request.predicate = [NSPredicate predicateWithFormat:@"exercise == %@",exercise];
    [request setPropertiesToGroupBy:[NSArray arrayWithObject:@"date"]];
    // Execute the fetch.
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    NSLog(@"%@",objects);

最佳答案

只需添加“日期”作为另一个要获取的属性:

[request setPropertiesToFetch:@[expressionDescription, @"date"]];

关于ios - 如何获取在 CoreData 中获取平均值的实体属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17854043/

相关文章:

ios - 如何从 NSString 中的句子中提取 URL?

ios - 即使 iPad 处于纵向模式,如何强制 iPad 外的电视处于横向模式

ios - 动态更改数据源导致 deleteRowsAtIndexPaths :indexes to crash

ios - Firebase 观察事件类型 :FIRDataEventTypeChildChanged callback never called

iphone - 我怎样才能让我的 UITableViewCell 包含两个标签?

ios - UIView removeFromSuperview 内部动画正确

ios - tableHeaderView UISearchBar 不显示

ios - 在 Collection View 中执行 numberof sections 时崩溃

ios - 如何下载 Vuforia 应用程序的数据集?

ios - 关于 iOS 中全局变量的替代方法(使用类方法和变量)