0

I have this error. I know some people have answered this on other threads but the answers given did not seem to work for me.

Here is my code:

The People class:

class People: NSObject, NSCoding {

    var firstName : String
    var lastName : String
    var events : [Event]
    init(firstName: String, lastName: String) {

        self.firstName = firstName
        self.lastName = lastName
        self.events = []
    }

    required init (coder aDecoder: NSCoder) {
         firstName = aDecoder.decodeObject(forKey: "firstName") as! String
        lastName = aDecoder.decodeObject(forKey: "lastName") as! String
        events = aDecoder.decodeObject (forKey: "events") as! [Event]


    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(firstName, forKey: "firstName")
        aCoder.encode(lastName, forKey: "lastName")        
        aCoder.encode(events, forKey: "events")
    }

}

Here is where I call to save the file:

func SaveMyPeople(){
    let Defaults = UserDefaults.standard
    let SavedData = NSKeyedArchiver.archivedData(withRootObject: ArrayPeople)
    Defaults.set(SavedData, forKey: "People") 
}

This is the Event Struct:

struct Event{
    var date : String
    var message : String
}

Any help I can get will be very much appreciated

1
  • This isn't the issue, but you're missing super.init(coder: aDecoder) in required init?(coder aDecoder: NSCoder) and also missing the ? in the signature of that init. Commented Mar 25, 2018 at 23:36

1 Answer 1

3

NSCoding requires the NSObjectProtocol. Only Classes can conform to NSObjectProtocol and you're using a Struct. ie:

struct Event{
    var date : String
    var message : String
}

Soroush Khanlou wrote a nice post about this here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.