核心数据sorting描述符与NSDate,iOS与斯威夫特

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

这是我现在的代码:

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) 

我应该如何改变这个sorting描述符以获得在“timeStamp”属性上具有较旧或较新date的对象?

谢谢。

要获取满足某些条件的所有对象,不需要sorting描述符而是谓词 ,例如:

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

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

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

Swift 3.0这对我来说没有问题

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