1
votes

My Core Data model has an NSDate attribute like here:

@interface DBVial : NSManagedObject
@property (nonatomic, retain) NSDate * updated_at;

How can I get the most recent (according to updated_at) record from all of the records of DBVial? Can I perform it by using NSPredicate? I know I could fetch all of them and then sort them and get the first one but is it possible to use only NSPredicate instead?

1

1 Answers

1
votes

Yup. No need to use NSPredicate, instead set the NSFetchRequest's sortDescriptor to sort records by date, and fetchLimit so you get only the most recent record. Like so:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"DBVial" 
                             inManagedObjectContext:yourManagedObjectContext];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"updated_at" ascending:NO]];
request.fetchLimit = 1;
NSError *error = nil;

DBVial *mostRecent =  [[context executeFetchRequest:request error:&error] lastObject];