Reputation: 1463
I have a Core Data database set up with a tableview and I'm trying to set it up where the the objects displayed in the table view are displayed in reverse chronological order. I'm trying to do this with NSSortDescriptor but can't figure out how to order it in reverse chronological order. Any ideas? Thanks.
Here's my code:
func getCoreData(){
var appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context : NSManagedObjectContext = appDel.managedObjectContext!
var req : NSFetchRequest = NSFetchRequest(entityName: "KeptQuotes")
var s = NSSortDescriptor(key: "quote", ascending: true)
req.sortDescriptors = [s]
var error : NSError?
let fetchedResults = context.executeFetchRequest(req, error: &error) as [NSManagedObject]?
if let results = fetchedResults {
keptQuotes = results
}else{
println("Could not fetch \(error), \(error!.userInfo)")
}
tableView.reloadData()
}
Upvotes: 3
Views: 2769
Reputation: 12768
Setup a date attribute in your entity of type NSDate, then set this attribute as your sort descriptor and set ascending to false.
let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
Upvotes: 8