Search code examples
iosswiftnspredicatensfetchrequestnssortdescriptor

NSPredicate: Getting the highest value


I've got the following:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedObjContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "RAS")
    var error: NSError?
    let predicate1 = NSPredicate(format: "%K AND %K == false",  "rasScore", "rasStatus")

    fetchRequest.predicate = predicate1

    do {...

This gives me ALL the records that conform to the parameters of the NSPredicate, but I want ONLY the record with the highest value in rasScore. How do I go about getting that? Is it possible to include that in the NSPredicate format?


Solution

  • Set the fetchLimit of your fetchRequest to 1 and use a descriptor to sort by value of "rasScore" descending like this:

    fetchRequest.fetchLimit = 1
    var highestSortDescriptor : NSSortDescriptor = NSSortDescriptor(key: "rasScore", ascending: false)
    fetchRequest.sortDescriptors = [highestSortDescriptor]