Swift 3中的NSCoding - 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [AppName.User encodeWithCoder:]

时间:2017-03-05 13:35:49

标签: swift swift3 nscoding nskeyedarchiver

我有实施NSCoding的问题。这是我的用户类代码:

public class User: NSCoder {
...

NSCoding方法:

解码器:

required public init(coder aDecoder: NSCoder) {
    self.deviceToken = aDecoder.decodeObject(forKey: kUserDeviceTokenKey) as? String
    self.postalCode = aDecoder.decodeObject(forKey:kUserPostalCodeKey) as? String
    self.latitude = aDecoder.decodeObject(forKey:kUserLatitudeKey) as? Float
    self.views = aDecoder.decodeObject(forKey:kUserViewsKey) as? Int
...

编码器:

func encode(with aCoder: NSCoder) {
    aCoder.encode(deviceToken, forKey: kUserDeviceTokenKey)
    aCoder.encode(postalCode, forKey: kUserPostalCodeKey)
    aCoder.encode(latitude, forKey: kUserLatitudeKey)
    aCoder.encode(views, forKey: kUserViewsKey)
...

保存&加载方法:

public func save(user : User){
    let encodedUser = NSKeyedArchiver.archivedData(withRootObject: user)
    UserDefaults.standard.set(encodedUser, forKey: kUserLogedKey)
}

public func getUserLoged()  -> User?{
    if let userData = UserDefaults.standard.object(forKey: kUserLogedKey),
        let user = NSKeyedUnarchiver.unarchiveObject(with: userData as! Data) as? User{
        print("DICT USER LOGED: \(user.dictionaryRepresentation())")
        return user
    }else {
        return nil
    }
}

我发现以下错误:

-[App.User encodeWithCoder:]: unrecognized selector sent to instance 0x101946e00
2017-03-05 14:22:47.540798 App[2642:750699] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[.User encodeWithCoder:]: unrecognized selector sent to instance 0x101946e00'

1 个答案:

答案 0 :(得分:2)

感谢@vadian提供解决方案:

我换了:public class User: NSCoder 通过:public class User: NSObject, NSCoding