核心数据排序描述符与NSDate,iOS与Swift

前端之家收集整理的这篇文章主要介绍了核心数据排序描述符与NSDate,iOS与Swift前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图根据日期属性过滤核心数据对象.

这是我目前的代码

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”属性上具有较旧或较新日期的对象?

谢谢.

解决方法

获取满足某些条件的所有对象,您不需要 @H_301_18@排序描述符但是谓词,例如:
let predicate = NSPredicate(format: "timeStamp < %@",date)
fetchRequest.predicate = predicate

您需要一个排序描述符来按指定的顺序获取对象,@H_301_18@例如:

let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp",ascending: true)
let sortDescriptors = [sectionSortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
原文链接:https://www.f2er.com/iOS/333339.html

猜你在找的iOS相关文章