我想知道是否有人可以向我展示如何在具有核心数据的表视图中保存数据?
我有一个需要在表视图中存储大量用户输入的应用程序。我一直在使用UserDefault,但我不应该这样做。我尚未导入核心数据,因为我不知道如何使用它来存储来自用户输入的数据以及如何从核心数据中获取数据以在表格视图中显示。
我将用户输入保存到logs
数组中。
var logs = [String]()
var userData = false
@IBOutlet weak var TableLogs: UITableView!
@IBAction func save(_ sender: Any) {
let a = (StartKm.text! as NSString).intValue
let b = (StartKm.text! as NSString).floatValue
let sum = a * 2
let sumb = b * 2
overallTrip.text = "\(sum)"
overallTrip.text = "\(sumb)"
let encodedData = NSKeyedArchiver.archivedData(withRootObject: userData)
userData = true
UserDefaults.standard.set(encodedData, forKey: "userData")
if StartKm.text == "" {
StartKm.backgroundColor = UIColor.red
}else{
StartKm.backgroundColor = UIColor.white
logs.append(overallTrip.text!)
UserDefaults.standard.set(overallTrip.text, forKey: "overall")
UserDefaults.standard.synchronize()
}
let myAlert = UIAlertController(title:"FYI", message:"You have \(5000 - sumb)KM left", preferredStyle: UIAlertControllerStyle.alert)
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.textLabel?.text = logs[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath){
if editingStyle == UITableViewCellEditingStyle.delete {
logs.remove(at: indexPath.row)
UserDefaults.standard.set(logs, forKey: "overall")
}
TableLogs.reloadData()
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "CarKmd") {
// var vc = segue.destination as! CarKm
let viewcontroller = storyboard?.instantiateViewController(withIdentifier: "CarKmd")
self.navigationController?.pushViewController(viewcontroller!, animated: true)
}
}
}