setPropertiesToFetch返回'无效的keypath表达式'错误

时间:2016-02-08 06:41:29

标签: ios core-data

我正在尝试以最基本的形式使用分组核心数据功能:

- (NSFetchedResultsController *)fetchedResultsController {

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSExpression *reviewNumKeyExpression = [NSExpression expressionForKeyPath:@"review_num"];
    NSExpression *reviewMaxExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:reviewNumKeyExpression]];

    NSExpressionDescription *maxReviewED = [[NSExpressionDescription alloc] init];
    [maxReviewED setName:@"maxReview"];
    [maxReviewED setExpression:reviewMaxExpression];
    [maxReviewED setExpressionResultType:NSInteger32AttributeType];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Group" inManagedObjectContext:managedObjectContext];

    [fetchRequest setResultType:NSDictionaryResultType];
    [fetchRequest setReturnsDistinctResults:YES];
    [fetchRequest setEntity:entity];

    NSAttributeDescription *groupId = [entity.propertiesByName objectForKey:@"group_id"];
    NSArray *propertiesToFetch = [NSArray arrayWithObjects:groupId, maxReviewED, nil];
    [fetchRequest setPropertiesToFetch:propertiesToFetch];
    [fetchRequest setPropertiesToGroupBy:propertiesToFetch];
...

运行此代码时,出现以下错误:

  

由于未捕获的异常而终止应用   ' NSInvalidArgumentException',原因:'无效的keypath表达式   ((),名称maxReview,   isOptional 1,isTransient 0,entity(null),renamingIdentifier   maxDepartment,validation predicates(),warnings(),   传递给的versionHashModifier(null)userInfo {})   setPropertiesToFetch

我想我错过了API的内容,所以非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我认为错误消息错误:问题出在setPropertiesToGroupBy,而不是setPropertiesToFetch。您无法按计算值(maxReview)进行分组,但我怀疑您确实希望:如果您希望每个review_num的最大值groupId,则只需要{{1} } groupId

propertiesToGroupBy