我试图根据日期属性过滤核心数据对象。

这是我当前的代码:

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)
}

但是我在行上得到了一个错误:
let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp < %@",date)

如何更改此排序描述符,以在“timeStamp”属性上获取具有较旧或较新日期的对象?

谢谢你。

最佳答案

要获取满足某些条件的所有对象,您不需要
排序描述符,但一个谓词,例如:

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

您需要一个排序描述符以指定顺序获取对象,
例如:
let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: true)
let sortDescriptors = [sectionSortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors

关于ios - 带有NSDate的核心数据排序描述符,带有Swift的iOS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30511999/

10-09 10:14