Jaco Griesel
Jaco Griesel

Reputation: 375

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?

Upvotes: 2

Views: 1543

Answers (1)

MarkHim
MarkHim

Reputation: 5766

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]

Upvotes: 8

Related Questions