Core Data - How to fetch an entity with max value property

Eyal picture Eyal · May 1, 2012 · Viewed 22.9k times · Source

I have a entity Person with a property personId (personId is unique)

How can I fetch the Person with the max personId?

(I want to fetch the person itself not the value of the property)

Answer

hypercrypt picture hypercrypt · May 1, 2012

You set the fetchLimit to 1 and sort by personId in descending order. E.g.:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Person"];

fetchRequest.fetchLimit = 1;
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"personId" ascending:NO]];

NSError *error = nil;

id person = [managedObjectContext executeFetchRequest:fetchRequest error:&error].firstObject;