问题:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Demo1.UserInfo encodeWithCoder:]: unrecognized selector sent to instance 0x610000470e40'
这表示没有找到encodeWithCoder这个方法,有以下几种情况
①没有继承NCoding这个类
②没有写encodeWithCoder这个方法(swift3.0中已改成encode())
解决方式:在UserInfo类中继承NCoding协议,并实现两个方法,具体如下
import UIKit class UserInfo: NSObject ,NSCoding{
var name:String
var age:String //构造方法
init(name:String = "",age:String = "") {
self.name = name
self.age = age
} //解析方法
required init(coder aDecoder:NSCoder) {
self.name = aDecoder.decodeObject(forKey: "Name") as! String
self.age = aDecoder.decodeObject(forKey: "Age") as! String
} //将信息编码成object
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "Name")
aCoder.encode(age,forKey:"Age")
}
}