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

前端 未结 7 800
误落风尘
误落风尘 2020-12-05 02:06

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 f

7条回答
  •  我在风中等你
    2020-12-05 02:39

    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;
    

提交回复
热议问题