我正在尝试将一组自定义对象从 iOS 传输到 watchkitextension。
了解为了做到这一点,需要对数据进行编码。虽然解码时出错。
开始了:
自定义对象:
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)
}
}
带有数组的类:
@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)
}
}
创建示例对象,附加到数组,然后编码:
let aPerson:Person? = Person(PersonName: "Martin", PersonAge: 50, joined: NSDate())
Group.sharedInstance.Persons.append(aPerson!)
let encodedData = NSKeyedArchiver.archivedDataWithRootObject(Group.sharedInstance)
在这里我得到错误“执行被中断 - 原因信号 SIGABRT”
let decodedData = NSKeyedUnarchiver.unarchiveObjectWithData(encodedData) as? Group