我正在创建一个ios应用程序,该应用程序每天都会向我显示一组用户特定的任务,单击这些任务可以将其删除以显示其完成情况。我将任务保存在核心数据中,然后单击删除表视图行。我不会按照用户定义的方式删除coredata中的数据,而是需要每天重新加载。如果应用在新的一天打开,我使用newDay()函数来决定从coredata加载数据。我应该怎么做才能记住当天完成了哪些任务?我是否需要创建另一个实体来记住哪些任务已完成,或者是否有更简单的方法?

var tasks: [NSManagedObject] = []
let defaults = UserDefaults.standard
var calender = Calendar.current

override func viewDidLoad() {
    super.viewDidLoad()

    title = "DailyTasker"
    navigationItem.leftBarButtonItem = editButtonItem

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let checkDate = newDay()
    if checkDate{

    //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Task")

    //3
    do {
        tasks = try managedContext.fetch(fetchRequest)
        defaults.set(Date(), forKey: "LastRun")
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
    }
}

func newDay() -> Bool{
    if let lastRun = defaults.object(forKey: "LastRun") as? Date{
        if !calender.isDateInToday(lastRun){
            return true
        } else {
            return false
        }
    } else {
        return true
    }

}


@IBAction func addName(_ sender: UIBarButtonItem) {
    let alert = UIAlertController(title: "New Task",
                                  message: "Add a new task",
                                  preferredStyle: .alert)

    let saveAction = UIAlertAction(title: "Save",
                                   style: .default) {
                                    [unowned self] action in

                                    guard let textField = alert.textFields?.first,
                                        let nameToSave = textField.text else {
                                            return
                                    }

                                    self.save(name: nameToSave)
                                    self.tableView.reloadData()
    }

    let cancelAction = UIAlertAction(title: "Cancel",
                                     style: .default)

    alert.addTextField()

    alert.addAction(saveAction)
    alert.addAction(cancelAction)

    present(alert, animated: true)
}

func save(name: String) {

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    // 1
    let managedContext =
        appDelegate.persistentContainer.viewContext

    // 2
    let entity =
        NSEntityDescription.entity(forEntityName: "Task",
                                   in: managedContext)!

    let task = NSManagedObject(entity: entity,
                               insertInto: managedContext)

    // 3
    task.setValue(name, forKeyPath: "name")

    // 4
    do {
        try managedContext.save()
        tasks.append(task)
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return tasks.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let task = tasks[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "TaskerCell", for: indexPath)
    cell.textLabel?.text = task.value(forKeyPath: "name") as? String

    return cell
}

 // Override to support editing the table view.
 override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
 if editingStyle == .delete {
 // Delete the row from the data source
 tasks.remove(at: indexPath.row)
 tableView.deleteRows(at: [indexPath], with: .fade)
 } else if editingStyle == .insert {

 }
 }

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tasks.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .fade)
}


}

最佳答案

您可以在任务中添加日期属性,例如,将其命名为lastDone。然后,您将其设置为任务完成时的当前日期时间,并且在获取任务实例时也使用谓词,以便仅获得今天未完成的任务。

 task.lastDone = Date()


我不确定如何定义“今天”,但是this question应该可以帮助您创建一个正确过滤任务的谓词,尽管您可能还希望包含lastDone为null的任务。

10-06 07:49