Reputation: 118
I am trying to make an alarm clock app to learn how to work with saving arrays of custom objects.
I have my project setup with a custom 'Alarm' object that contains all the information about each alarm and I have created a class that inherits NSObject and NSCoding.
Here is the Alarm Object Class
import Foundation
class Alarm : NSObject {
var name : String
var active : Bool
var days : [String]
var sound : [String:Int] //Will change later...... I think?.....
var time : NSDate
init(name : String, active : Bool, days : [String], sound : [String:Int], time : NSDate) {
self.name = name
self.active = active
self.days = days
self.sound = sound
self.time = time
}
}
Heres my Custom Class that inherits NSObject and NSCoding
import UIKit
class Alarms: NSObject, NSCoding {
var alarmList : [Alarm]
init(alarmList : [Alarm]) {
self.alarmList = alarmList
}
required convenience init?(coder decoder: NSCoder) {
guard let alarmList = decoder.decodeObjectForKey("alarms") as? [Alarm]
else { return nil }
self.init(
alarmList : alarmList
)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(alarmList, forKey: "alarms")
}
}
I have a save function connected to a button for testing purposes. Here is that function.
func save(sender: AnyObject?) {
//Save with NSKeyArchiver
print("Save: \(path)")
var success = false
success = NSKeyedArchiver.archiveRootObject(alarmItems, toFile: path)
if success {
print("Saved Alarms")
} else {
print("Didn't Save Alarms")
}
}
I reference a path variable this is set in my ViewDidLoad() Function
path = fileInDocumentsDirectory("alarms.plist")
Now when I run the app and add an alarm and click the save button it crashes with the following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SavingAlarmsApp.Alarm encodeWithCoder:]: unrecognized selector sent to instance 0x7fbe3ac789a0'
what am I doing wrong here? I have been able to save an array of strings just fine with this code.
Upvotes: 1
Views: 2681
Reputation: 865
You just forgot about Alarm class. It should implement NSCoding protocol too.
Upvotes: 4