CallOfOrange CallOfOrange - 2 years ago 89
iOS Question

How to sort and limit with NSPredicate in CoreData?

I want to fetch five records saved in Core Data and sorted by a

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?

Answer Source

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];


let sort = NSSortDescriptor(key: "recordingTime", ascending: true)
request.sortDescriptors = [sort]
request.fetchLimit = 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download