2

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.

JsW
  • 1,682
  • 3
  • 22
  • 34

1 Answers1

6

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
Nirav D
  • 71,513
  • 12
  • 161
  • 183