I want to fetch five records saved in Core Data and sorted by a Date
type attribute named "recordingTime".
For example, In MySql, we can simply add limit = 5
to set a limit.
So, how to sort and limit with NSPredicate?
Thanks.
You can use sortDescriptors
and fetchLimit
property of NSFetchRequest
for that.
Objective C:
//Set sort
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"recordingTime" ascending:YES];
[request setSortDescriptors: @[sort]];
[request setFetchLimit:5];
Swift:
let sort = NSSortDescriptor(key: "recordingTime", ascending: true)
request.sortDescriptors = [sort]
request.fetchLimit = 5