按日期和字符对核心数据属性进行排序

时间:2016-07-21 18:56:53

标签: ios iphone swift xcode core-data

我正在尝试搜索我的核心数据,默认情况下会搜索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;
}

1 个答案:

答案 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]

应按升序标题排序,然后按降序日期排序(即具有相同标题的项目应按日期降序排列)。