Core data predicate with group and MAX()

后端 未结 2 664
野趣味
野趣味 2021-01-24 15:34

I have an object in core data that has 2 fields: Name and Date. Each time a person checks in it saves their name and the time they did it.

Is there a way to get a list

相关标签:
2条回答
  • 2021-01-24 15:43

    Beginning from iOS 5.0 / OS X 10.7 NSFetchRequest class includes the setPropertiesToGroupBy: instance method, which allow to create aggregated requests on persistent storage level.

    You would have to set NSDictionaryResultType as the result type, thus telling NSFetchRequest object to return NSDictionary objects with aggregated data instead of managed objects.

    Example code for max() requests:

    [request setResultType:NSDictionaryResultType];
    
    NSExpression *dateKeyExpression = [NSExpression expressionForKeyPath:@"date"];
    NSExpression *maxDateExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:dateKeyExpression]];
    NSExpressionDescription *maxDateED = [[NSExpressionDescription alloc] init];
    [maxDateED setExpression:maxDateExpression];
    [maxDateED setName:@"maxDate"];
    [maxDateED setExpressionResultType:NSDateAttributeType];
    
    NSAttributeDescription *clientName = [[self entityDescription].attributesByName objectForKey:@"clientName"];
    [request setPropertiesToFetch:[NSArray arrayWithObjects:clientName, maxDateED, nil]];
    [request setPropertiesToGroupBy:[NSArray arrayWithObject:clientName]];
    
    0 讨论(0)
  • No not easily since Core Data is an object graph first. You could do it by grabbing a distinct set of the names and then querying for the max for each via a sort.

    The best answer is to break it into two tables otherwise it is going to be computationally expensive each time you try and resolve this.

    OR/M Layer

    Don't think of it as an OR/M layer. Core Data is an object graph; full stop.

    The fact that it happens to persist to a database structure as one of its persistence options is secondary.

    The issue in your question is that you are trying to use an Object Graph as a database. In that situation I get to use a phase that is very frequently attributed to me:

    "You're doing it wrong." :)

    0 讨论(0)
提交回复
热议问题