Am trying to transfer an array of custom objects from iOS to watchkitextension.
Understood that in order to do so, data needs to be encoded. Am though getting error when decoding.
Here we go:
The custom object:
final class Person: NSObject {
var PersonName:String = ""
var PersonAge:Int = 0
var joined:NSDate = NSDate()
init(PersonName: String, PersonAge:Int, joined:NSDate){
self.PersonName = PersonName
self.PersonAge = PersonAge
self.joined = joined
super.init()
}
}
extension Person: NSCoding {
private struct CodingKeys {
static let PersonName = "PersonName"
static let PersonAge = "PersonAge"
static let joined = "joined"
}
convenience init(coder aDecoder: NSCoder) {
let PersonName = aDecoder.decodeObjectForKey(CodingKeys.PersonName) as! String
let PersonAge = aDecoder.decodeIntForKey(CodingKeys.PersonAge) as! Int
let joined = aDecoder.decodeDoubleForKey(CodingKeys.joined) as! NSDate
self.init(PersonName: PersonName, PersonAge: PersonAge, joined: joined)
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(PersonName, forKey: CodingKeys.PersonName)
encoder.encodeObject(PersonAge, forKey: CodingKeys.PersonAge)
encoder.encodeObject(joined, forKey: CodingKeys.joined)
}
}
The class with the array:
@objc(Group)
final class Group: NSObject {
static let sharedInstance = Group()
var Persons:[Person] = []
required override init() {
super.init()
}
init (Persons:[Person]){
self.Persons = Persons
super.init()
}
}
extension Group: NSCoding {
private struct CodingKeys {
static let Persons = "Persons"
}
convenience init(coder aDecoder: NSCoder) {
let Persons = aDecoder.decodeObjectForKey(CodingKeys.Persons) as! [Person]
self.init(Persons: Persons)
self.Persons = aDecoder.decodeObjectForKey(CodingKeys.Persons) as! [Person]
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(Persons, forKey: CodingKeys.Persons)
}
}
Creating example object, append to array, then encode:
let aPerson:Person? = Person(PersonName: "Martin", PersonAge: 50, joined: NSDate())
Group.sharedInstance.Persons.append(aPerson!)
let encodedData = NSKeyedArchiver.archivedDataWithRootObject(Group.sharedInstance)
And here I get the error "execution was interrupted - reason signal SIGABRT"
let decodedData = NSKeyedUnarchiver.unarchiveObjectWithData(encodedData) as? Group