0

I am creating an app that you add a task pressing a button, the cell has a custom cell that populates the tableview with the information the user type in the textviews, the problem is that I am having a hard time to save the array using UserDefaults(the only method I know), the app crashes when I press the addButton, could you guys point to me to the right direction please ? Thanks.

I have a customCell here:

 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
}

I call this function to append to the array when I press the button but I am getting a error in userDefaults.

class TaskManager: NSObject
    {
        var tasks = [task]()

        func addTask(name: String, desc: String, image: UIImage)
        {
            tasks.append(task(name: name, desc: desc, image: image))
        }
    }

I want to call the function to save the data when I press the button

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()

    }

0 Answers0