我已经将项目迁移到Swift 3,NSKeyedArchiver
但无法正常工作。当尝试像这样解码对象时,我实际上遇到了运行时错误:
let startDayTime = aDecoder.decodeObject(forKey: Key.startDayTime) as! Int
它在Xcode 7.3的Swift 2.2中完美运行。还有其他人遇到过这样的麻烦吗?
PS我在模拟器和设备上都有此错误。
更新:我通过使用decodeInteger(forKey key: String)
而不是解决了这个问题decodeObject(forKey key: String)
。出于某种原因,尽管它在Swift 2.2中确实做到了,但AnyObject在Swift 3中并未转换为Integer
似乎只有在Swift 2到Swift 3的更新边界上才发生这种情况,当NSKeyedArchiver
在Swift 2中用a打开在Swift 2中存档的NSData blob时,NSKeyedUnarchiver
我猜是在Swift 2上,Bool
andInt
编码为NSNumber
,但是在Swift中3,它们被编码为原始Bool
和Int
类型。我相信以下测试支持此主张:
这在Swift 3中可以取消Bool
对Swift 2中的编码的存档,但是nil
如果Bool是在Swift 3中编码的,则返回:
let visible = aDecoder.decodeObject(forKey: "visible") as? Bool
这在Swift 3中可以取消对Swift 3中的Bool
编码进行存档,但是如果Bool在Swift 2中进行了编码,则会崩溃:
let visible = aDecoder.decodeBool(forKey: "visible")
我的解决方案是:
let visible = aDecoder.decodeObject(forKey: "visible") as? Bool ?? aDecoder.decodeBool(forKey: "visible")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句