我正在创建一个应用程序,你按一个按钮添加一个任务,单元格有一个自定义单元格,用用户在textview中输入的信息填充tableview,问题是我很难保存使用UserDefaults(我知道的唯一方法)的数组,当我按下addButton时应用程序崩溃,你们可以指向我正确的方向吗?感谢。
我在这里有一个customCell:
import UIKit
class CelulaCustomizada: UITableViewCell //custom cell {
@IBOutlet weak var imagemDefesa: UIImageView!
@IBOutlet weak var nomeLabelDefesa: UILabel!
@IBOutlet weak var levelLabelDefesa: UILabel!
}
import UIKit
var taskMgr: TaskManager = TaskManager()
struct task
{
var name = "Un-Named"
var desc = "Un-Described"
var image : UIImage
}
当我按下按钮但是我在userDefaults中收到错误时,我调用此函数追加到数组。
class TaskManager: NSObject
{
var tasks = [task]()
func addTask(name: String, desc: String, image: UIImage)
{
tasks.append(task(name: name, desc: desc, image: image))
}
}
我想在按下按钮
时调用该功能来保存数据class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate
{
@IBOutlet weak var txtTask: UITextField!
@IBOutlet weak var txtDesc: UITextField!
@IBOutlet weak var tableViewTasks: UITableView!
override func viewDidAppear(_ animated: Bool)
{
}
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func addButton(_ sender: Any)
{
taskMgr.addTask(name: txtTask.text!, desc: txtDesc.text!, image: #imageLiteral(resourceName: "cannon"))
self.view.endEditing(true)
txtTask.text = ""
txtDesc.text = ""
/*its giving me an error and crashing the app saying that "" 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object (
"MyTaskClash.task(name: \"\", desc: \"\", image: <UIImage: 0x60800009d3d0>, {199, 170})"
) for key tasks' */
UserDefaults.standard.set(taskMgr.tasks, forKey: "tasks")
tableViewTasks.reloadData()
}