我正在尝试搜索我的核心数据,默认情况下会搜索title属性,但我也需要按date
对结果进行排序。
我的代码会搜索title
属性,但如何制作两个predicates
并将其与context
相关联?
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string)
//Load data from Core Data
let appDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
context = appDel.managedObjectContext
do {
request = NSFetchRequest(entityName: "Event")
let sort:NSSortDescriptor = NSSortDescriptor(key:"title", ascending: true)
request.sortDescriptors = [sort]
let searchPredicate = NSPredicate(format: "title CONTAINS[c] %@", prospectiveText)
request.predicate = searchPredicate
results = try context.executeFetchRequest(request)
animateTableCell()
} catch {
print("ERROR")
}
return true;
}
答案 0 :(得分:2)
在选择或排序中,您是否感兴趣并不是100%明确。谓词用于确定要选择的记录,排序描述符用于对结果进行排序。
对于排序,request.sortDescriptors
是一组描述符。所以你可以有多个描述符,例如:
let sort:NSSortDescriptor = NSSortDescriptor(key:"title", ascending: true)
let sort2:NSSortDescriptor = NSSortDescriptor(key:"date", ascending: false)
request.sortDescriptors = [sort, sort2]
应按升序标题排序,然后按降序日期排序(即具有相同标题的项目应按日期降序排列)。