正确的方法从CoreData获取过滤数据以在swift中填充UITableView

时间:2018-03-25 12:26:20

标签: ios swift core-data

我正在保存实体中的数据,属性是字符串数量,字符串类别,日期日期和字符串子类别,现在我想从CoreData获取上个月的信息,而不是填充我的UITableView。 我的代码如下所示:

let fetchRequest = NSFetchRequest<Outcome>(entityName: "Outcome")
        let startDate = Date().startOfMonth()
        let endDate = Date().endOfMonth()
        let sort = NSPredicate(format: "date => %@ && date <= %@" , startDate as NSDate, endDate as NSDate)
        fetchRequest.predicate = sort
        do {
            self.outcomes = try context.fetch(fetchRequest)
        } catch {
            print("Cannot fetch Expenses")
        }
        self.tableView.reloadData()  

startDate和endDate来自Date()扩展名:

extension Date {    
    func startOfMonth() -> Date {
        return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!
    }

    func endOfMonth() -> Date {
        return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())!
    }
}


extension FirstViewController{
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return outcomes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "OutcomeTableViewCell") as? OutcomeTableViewCell else { return UITableViewCell() }
    let outcome = outcomes[indexPath.row]
    cell.configureCell(outcome: outcome)
    return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .none
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (rowAction, indexPath) in
        self.removeItem(atIndexPath: indexPath)
        self.fetchCoreDataObjects()
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
    deleteAction.backgroundColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
    return [deleteAction]
}

}

所以我最后空了UITableView,我不明白为什么 感谢您的帮助。

0 个答案:

没有答案