0

I am new to coding. I'm trying to create a notes app.

My code:

import UIKit

class TableViewController: UITableViewController, NoteViewDelegate {

    var arrNotes = [[String:String]]()
    var selectedIndex = -1

    override func viewDidLoad() {
        super.viewDidLoad()

        if let newNotes = UserDefaults.standard.array(forKey: "notes") as? [[String:String]]  {
            arrNotes = newNotes                
        }           
    }

    @IBAction func newNote() {
        self.selectedIndex = 0
        self.tableView.reloadData()
        saveNotesArray()
        performSegue(withIdentifier: "showEditorSegue", sender: nil)         
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let notesEditorVC = segue.destination as! NotesViewController
        notesEditorVC.navigationItem.title = arrNotes[self.selectedIndex]["title"]
        notesEditorVC.strBodyText = arrNotes[self.selectedIndex]["body"]
        notesEditorVC.delegate = self            
    }
    
    func didUpdateNoteWithTitle(newTitle: String, andBody newBody: String) {
        self.arrNotes[self.selectedIndex]["title"] = newTitle
        self.arrNotes[self.selectedIndex]["body"] = newBody
        self.tableView.reloadData()
        saveNotesArray()
    }
}

Whenever I click on the Add button, my app crashes and out of bound error occurs in prepare method and I am unable to run my code.

How can I correct my logic?

Error line :

notesEditorVC.navigationItem.title = arrNotes[self.selectedIndex]["title"]
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
Manan Jain
  • 27
  • 5
  • Your array is empty, so you need to append a new element to it to avoid an out of bounds error. I would also suggest you use an array of a struct rather than an array of dictionaries. – Paulw11 Jul 06 '20 at 07:55
  • 1
    Show us the saveNotesArray function. It could have something to do with the way you're saving the array. – JasonJotted Jul 07 '20 at 02:51
  • ` func saveNotesArray() { UserDefaults.standard.set(arrNotes,forKey: "notes") UserDefaults.standard.synchronize() }`. @JasonJotted – Manan Jain Jul 12 '20 at 14:10

0 Answers0