2
votes

I want to retrieve the most recently added record from CoreData. I was wondering if that's possible using NSPredicate? If so, how?

e.g. i have a one-to-many relationship between Department and Staff, and i want to fetch the Staff record that was most recently employed. The Staff table has a date field which can be used.

I don't want to fetch all the Staff records and then look for the right one. Note that CoreData stores the related records in an NSSet.

1

1 Answers

5
votes

I don't think that a predicate will do what you are asking here. Instead, what you can do is fetch a single record with the sort descriptor set to sort the dates in descending order. You need to modify your fetch request to include the following:

NSSortDescriptor *dateSort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:dateSort]];
[fetchRequest setFetchLimit:1];

This should get you the Staff object with the most recent date attribute. Note that if you are using an SQLite store, then the sorting is done at the SQLite layer and only the single result is fetched.