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;
}
Written by Zachary Waldowski
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Core data
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#