Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Array of Custom Object

Tags:

arrays

ios

swift

I am try to save and retrieve notes data with custom object called Sheet. But I am having crashes when it runs. Is this the correct way to do it or is there any other ways to solve this?

The Sheet Class

class Sheet {
    var title = ""
    var content = ""
}

Here is the class for UITableViewController

class NotesListTableVC: UITableViewController {

    var notes = [Sheet]()

    override func viewDidLoad() {
        super.viewDidLoad()

        if let newNotes = UserDefaults.standard.object(forKey: "notes") as? [Sheet] {
            //set the instance variable to the newNotes variable
            notes = newNotes
        }
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        return notes.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "notesCELL", for: indexPath)

        cell.textLabel!.text = notes[indexPath.row].title

        return cell
    }

    // Add new note or opening existing note
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "editNote" {
            var noteContentVC = segue.destination as! NoteContentVC
            var selectedIndexPath = tableView.indexPathForSelectedRow
            noteContentVC.note = notes[selectedIndexPath!.row]
        }
        else if segue.identifier == "newNote" {
            var newEntry = Sheet()
            notes.append(newEntry)
            var noteContentVC = segue.destination as! NoteContentVC
            noteContentVC.note = newEntry
        }
        saveNotesArray()
    }

    // Reload the table view
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.tableView.reloadData()
    }

    // Deleting notes
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        notes.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
    }

    // Save the notes
    func saveNotesArray() {
        // Save the newly updated array
        UserDefaults.standard.set(notes, forKey: "notes")
        UserDefaults.standard.synchronize()
    }

}

And where should I call the saveNotesArray function?

like image 300
Francis Avatar asked Jan 02 '23 21:01

Francis


1 Answers

You are trying to save an array of custom objects to UserDefaults. Your custom object isn't a property list object You should use Codable to save non-property list object in UserDefaults like this.

Swift 4

Custom Class

class Sheet: Codable {
  var title = ""
  var content = ""
}

ViewController.swift

class ViewController: UIViewController {

    var notes = [Sheet]()

    override func viewDidLoad() {
        super.viewDidLoad()

        getSheets()
        addSheets()
        getSheets()
    }
    func getSheets()
    {
        if let storedObject: Data = UserDefaults.standard.data(forKey: "notes")
        {
            do
            {
                notes = try PropertyListDecoder().decode([Sheet].self, from: storedObject)
                for note in notes
                {
                    print(note.title)
                    print(note.content)
                }
            }
            catch
            {
                print(error.localizedDescription)
            }
        }
    }
    func addSheets()
    {
        let sheet1 = Sheet()
        sheet1.title = "title1"
        sheet1.content = "content1"

        let sheet2 = Sheet()
        sheet2.title = "title1"
        sheet2.content = "content1"

        notes = [sheet1,sheet2]
        do
        {
            UserDefaults.standard.set(try PropertyListEncoder().encode(notes), forKey: "notes")
            UserDefaults.standard.synchronize()
        }
        catch
        {
            print(error.localizedDescription)
        }
    }
}
like image 94
RajeshKumar R Avatar answered Jan 05 '23 14:01

RajeshKumar R