Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data sort descriptor with NSDate, iOS with Swift

I am trying to filter core data objects depending on a date attribute.

This is my current code:

func getFetchedResultController(selectedEntity: NSString){

    let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedObjectContext: NSManagedObjectContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest()

    let entity = NSEntityDescription.entityForName(selectedEntity as String, inManagedObjectContext: managedObjectContext)

    fetchRequest.entity = entity

    fetchRequest.fetchBatchSize = 20

    let date = NSDate()

    let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp < %@",date)

    let sortDescriptors = [sectionSortDescriptor] //, secondSortDescriptor]

    fetchRequest.sortDescriptors = sortDescriptors

    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

    aFetchedResultsController.delegate = self
    self.fetchedResultsController = aFetchedResultsController

    var error: NSError? = nil
    if !self.fetchedResultsController.performFetch(&error) {
        abort()
    }

 print(fetchedResultsController.fetchedObjects?.count ?? 0)
}

But I get an error at line:

let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp < %@",date)

How should I change this sort descriptor to get the objects that have an older or a newer date on the "timeStamp" attribute?

Thank you.

like image 424
mvasco Avatar asked May 28 '15 16:05

mvasco


2 Answers

To fetch all objects satisfying some condition you don't need a sort descriptor but a predicate, for example:

let predicate = NSPredicate(format: "timeStamp < %@", date)
fetchRequest.predicate = predicate

You need a sort descriptor to get the objects in a specified order, for example:

let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: true)
let sortDescriptors = [sectionSortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
like image 165
Martin R Avatar answered Oct 27 '22 11:10

Martin R


Swift 3.0 This works with no problem for me

let fec:NSFetchRequest = YourEntity.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "type", ascending: true)
fec.sortDescriptors = [sortDescriptor]
let items = try! context.fetch(fec)
like image 40
Murat Akdeniz Avatar answered Oct 27 '22 09:10

Murat Akdeniz