Last Updated: February 25, 2016
·
3.707K
· zwaldowski

Maximum value for attribute in Core Data

+ (int32_t)maximumPositionInContext:(NSManagedObjectContext *)context {
    // sample using attribute named "position" on entity "Item"

    NSFetchRequest *request = [NSFetchRequest new];
    request.entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:context];
    request.resultType = NSDictionaryResultType;
    // technically not necessary to set fetchLimit = 1, resultType could be (Item *) managed object

    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"position"];
    NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:" arguments: @[ keyPathExpression ]];
    NSExpressionDescription *expression = [NSExpressionDescription new];
    expression.name = @"maxPosition";
    expression.expression = maxExpression;

    // This changes the return value in valueForKey: below
    expression.expressionResultType = NSInteger32AttributeType;

    request.propertiesToFetch = @[ expression ];

    // Execute the fetch.
    NSError *error = nil;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    if (objects && objects.count) {
        return [[objects[0] valueForKey:@"maxPosition"] integerValue];
    }

    return -1;
}