This question is not the same as - Saving custom SWIFT class with NSCoding to UserDefaults and it is different because there are 2 classes that are connected to each other and I don't know to implement NSCoding for both of them.I am beginner and I have been trying for more than 6 hours to solve this problem.And btw this is not a duplicate because all the solutions on here are outdated. I have 2 main custom classes(super class and subclass) in my app and with UserDefaults I want to make so I can save data permanently.
The first class:
class Day {
var dayName: String
var subjects: [Subject]?
init(dayName: String) {
self.dayName = dayName
}
}
The second class:
class Subject: Day {
var subjectName: String
var startsAt: String?
init(dayName: String,subjectName: String) {
self.subjectName = subjectName
super.init(dayName: dayName)
}
}
I try to save a instance of Subject class like this:
UserDefaults.standard.set(Subject(dayName: "Monday",subjectName: "Programming"), forKey: "subject")
let savedSubject = UserDefaults.standard.object(forKey: "subject") as? Subject
print(savedSubject!.subjectName)
And then when I run the app I get a crash saying -
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object School_Class_Scedule.Subject for key subject'
I did a lot of research and found out that I should convert the subject to NSData but I don't know how to do that with swift 3 or 4 in XCode 9. Any help would be much appreciated. Thank you for saving my life and helping me my dream to become a reality.