我一直在使用苹果指南来保存swift中的数据,但是当我尝试编译它时,它告诉我这是不符合要求的。它应该基于苹果指南和其他代码。
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(firstName, forKey: "firstName")
aCoder.encodeObject(lastName, forKey: "lastName")
aCoder.encodeObject(phoneNumber, forKey: "phoneNumber")
aCoder.encodeObject(email, forKey: "email")
aCoder.encodeObject(address, forKey: "address")
}
required convenience init?(coder aDecoder: NSCoder) {
firstName = aDecoder.decodeObjectForKey("firstName") as! String
lastName = aDecoder.decodeObjectForKey("lastName") as! String
phoneNumber = aDecoder.decodeObjectForKey("phoneNumber") as! String
email = aDecoder.decodeObjectForKey("email") as! String
address = aDecoder.decodeObjectForKey("addressq") as! String
self.init(phoneNumber: phoneNumber, firstName: firstName, lastName: lastName, email: email, address: address)
}
因此,当我可以运行Apple的程序时,我不确定为什么它不符合要求。
编辑:所以问题似乎是我没有从NSObject继承我的类。这解决了这个问题。
答案 0 :(得分:0)
此处没有错误:
class Dog {
var firstName: String
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(firstName, forKey: "firstName")
}
init(firstName: String) {
self.firstName = firstName
}
required convenience init?(coder aDecoder: NSCoder) {
let x = aDecoder.decodeObjectForKey("firstName") as! String
self.init(firstName: x)
}
}
var d = Dog(firstName: "Rover")