Search code examples
iosobjective-cswiftcore-datanspredicate

How to sort and limit with NSPredicate in CoreData?


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.


Solution

  • 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