通过CoreData Swift 4中的Bool属性对获取结果进行排序

时间:2018-03-09 21:40:39

标签: ios sorting core-data swift4

我正在创建一个ToDo列表应用,并希望按优先级对tableviewcontroller进行排序。如果任务很重要,我希望它在待办事项列表之上,如果它在重要任务之下/之后并不重要。我一直试图弄清楚如何对此进行排序,但却未能如此。感谢一些帮助。

class ToDoTableViewController: UITableViewController {

var toDos : [ToDoCoreData] = []

override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewWillAppear(_ animated: Bool) {
    getToDos()
}

func getToDos() {
    if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext{

        if let coreDataToDos = try? context.fetch(ToDoCoreData.fetchRequest()) as? [ToDoCoreData] {
            if let theToDos = coreDataToDos {
                toDos = theToDos
                tableView.reloadData()
            }
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    let toDo = toDos[indexPath.row]

    if let name = toDo.name {

        if toDo.important {
            cell.textLabel?.text = "❗️" + name
        } else {
            cell.textLabel?.text = toDo.name
        }
    }
    return cell
}

1 个答案:

答案 0 :(得分:0)

更新getToDos()功能:

func getToDos() {
    if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext{

        let fetchRequest: NSFetchRequest<ToDoCoreData> = ToDoCoreData.fetchRequest()
        let descriptors = [NSSortDescriptor(key: "important", ascending: true)] // try true/false

        fetchRequest.sortDescriptors = descriptors

        if let coreDataToDos = try? context.fetch(fetchRequest) {
            if let theToDos = coreDataToDos {
                toDos = theToDos
                tableView.reloadData()
            }
        }
    }
}