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

时间:2015-05-28 16:17:08

标签: ios swift core-data

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

这是我目前的代码:

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)

如何更改此排序描述符以获取在&#34; timeStamp&#34;上的旧日期或更新日期的对象?属性?

谢谢。

3 个答案:

答案 0 :(得分:28)

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

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

您需要排序描述符才能按指定顺序获取对象, 例如:

let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: true)
let sortDescriptors = [sectionSortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors

答案 1 :(得分:3)

Swift 3.0 这对我来说没有问题

let fec:NSFetchRequest = YourEntity.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "type", ascending: true)
fec.sortDescriptors = [sortDescriptor]
let items = try! context.fetch(fec)

答案 2 :(得分:0)

> Swift4

func getLastDateFromEntries(entityName:String) -> [NSManagedObject]{
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    do {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        let sortDescriptors = NSSortDescriptor(key: "dueDate", ascending: false) // dueDate is key
        fetchRequest.sortDescriptors = [sortDescriptors]
        fetchRequest.fetchLimit = 1 // add limit
        let fetchedResults = try context.fetch(fetchRequest) as! [NSManagedObject]
        return fetchedResults
    }
    catch {
        print ("fetch task failed", error)
        return []
    }
    
}