Core data 子实体属性的核心数据最大值

Core data 子实体属性的核心数据最大值,core-data,Core Data,我知道我不应该将核心数据视为关系数据。但是使用SQL查询最容易解释我要做的事情 我想做的是从约束到实体子级的属性中获取最大值。在SQL中,类似于:从parentID=10的graphdata中选择max(valueY) 我正在做类似于上面SQL查询的事情,成功地排除了where(NSPredicate)部分 我将NSPredicate添加到代码中,认为它将排除我正在查看的KPI之外的graphdata对象。好吧,我猜不是,这不是我所看到的,它似乎什么也没做,真的 核心数据模型由多个KPI对象组成

我知道我不应该将核心数据视为关系数据。但是使用SQL查询最容易解释我要做的事情

我想做的是从约束到实体子级的属性中获取最大值。在SQL中,类似于:
从parentID=10的graphdata中选择max(valueY)

我正在做类似于上面SQL查询的事情,成功地排除了where(NSPredicate)部分

我将NSPredicate添加到代码中,认为它将排除我正在查看的KPI之外的graphdata对象。好吧,我猜不是,这不是我所看到的,它似乎什么也没做,真的

核心数据模型由多个KPI对象组成,每个对象包含一个GraphData对象数组。每个GraphData对象都包含一个valueX和一个valueY属性

我需要指定KPI对象的graphdata的最大值

这是我的代码,它基于苹果的一个核心数据片段:

NSManagedObjectContext *context = ...

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:GRAPH_DATA_ENTITY_NAME 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:@"ValueY"];

//MY WHERE KIND OF CLAUSE/PREDICATE WHICH ISN'T WORKING?
NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"kpiForGraphData == %@", self.kpi];
[request setPredicate:predicate];

// Create an expression to represent the function you want to apply
NSExpression *expression = [NSExpression expressionForFunction:@"max:"
                                                     arguments:[NSArray arrayWithObject: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:@"maxValueY"];
[expressionDescription setExpression:expression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType]; // For example, NSDateAttributeType

// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

// Execute the fetch.
NSError *error;
id requestedValue = nil;

NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
    // Handle the error.
}
else {
    if ([objects count] > 0) {
        requestedValue = [[objects objectAtIndex:0] valueForKey:@"maxValueY"];
    }
}

[expressionDescription release];
[request release];


return [requestedValue doubleValue];

到目前为止,我一直试图通过阅读文档、搜索谷歌和stackoverflow来帮助自己。我找到的所有东西要么选择实体(NSPredicates),要么使用函数选择值。我从来没有见过一个例子或一个解释做我想做的事情。我喜欢核心数据,但现在SQL对我来说似乎更简单。

我开始意识到我实际上做得对,而且我对数据的解释不正确。。。我的想法和解决方案是否正确?