0
votes

I am making a simple notes app and when starting the app it gives me the error, "NSArray element failed to match Swift Array Element Type". Though there are many other questions like this, none of them had the problem in a tableViewController when putting the

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

Here is my full code and the class for the array:

Code:

class TableViewController: UITableViewController {
    var noteTitles:[Note] = []

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, 
                            numberOfRowsInSection section: Int) -> Int {
        return noteTitles.count
    }

    override func tableView(tableView: UITableView, 
        cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", 
            forIndexPath: indexPath) as UITableViewCell

        cell.textLabel!.text = noteTitles[indexPath.row].title // Error here.

        return cell
    }   
}

And the Note Class:

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

Please help me and tell me what I am doing wrong and help me fix it. Thank you in advance!

Here is image as asked of NSCoding error:

code

Here is image of KeyedUnarchiver error:

code

2
Can you add the Note class implementation as well? - Mark
@Mark Sorry, I forgot to add, just added it. - Epic Gamer_1
How are you loading the values into the array of Notes ? The error message says that the array doesn't have Note objects in it. - Paulw11

2 Answers

0
votes

My first guess is you changed the Note class, and you're trying to load the old class from NSUserDefaults. What happens if you clear out NSUserDefaults first? (Either by changing the key you're using, or adding in a hard coded removeObjectForKey().

0
votes

array and dictionary for NSUserDefaults must have property list elements. so using custom objects for NSUserDefaults normally impossible.

you must use NSCoding, and NSKeyed(Un)Archiver for changed to NSData from array

How is this?

see here Encoding and Decoding Objects

// just examples
class Note: NSObject, NSCoding {
    var note: String = ""
// you must overriding init?(coder: NSCoder) and func encode(with: NSCoder)
    // for unarchiving from NSData
    required init?(coder aDecoder: NSCoder) {
        super.init()
        self.note = aDecoder.decodeObjectForKey("note")// just example
    }
    // for archiving to NSData
    func encode(coder aCoder: NSCoder) {
        aCoder.encodeObject(self.note, forKey: "note")
    }
}

set note titles (sorry for swift 3 statement. you can find right code with autocompletion)

let notesArchived = NSKeyedArchiver.archivedData(withRootObject: notes), forKey: "notes") // is NSData
// save notesArchived to NSUserDefaults

get note titles

let notesData = UserDefaults.standard.data(forKey: "notes")! // NSData
let notes = NSKeyedUnarchiver.unarchiveObject(with: notesData)

this possible to me