Core Data sort descriptor with NSDate, iOS with Sw

2020-08-21 19:09发布

问题:

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.

回答1:

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


回答2:

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)