NSKeyedArchiver在Swift 3(XCode 8)中不起作用 [英] NSKeyedArchiver does not work in Swift 3 ( XCode 8)

查看:92
本文介绍了NSKeyedArchiver在Swift 3(XCode 8)中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将项目迁移到Swift 3,并且NSKeyedArchiver无法正常工作.尝试像这样解码对象时,我实际上遇到了运行时错误:

I have migrated my project to Swift 3 and NSKeyedArchiver does not work. I actually have a runtime error when trying to decode object like this:

let startDayTime = aDecoder.decodeObject(forKey: Key.startDayTime) as! Int

它在Xcode 7.3的Swift 2.2中完美运行.还有其他人遇到这样的麻烦吗?

It worked perfectly in Swift 2.2 in Xcode 7.3. Has anybody else faced such troubles?

P.S.我在模拟器和设备上都遇到此错误.

P.S. I have this error on both Simulator and Device.

更新:我通过使用decodeInteger(forKey key: String)而不是decodeObject(forKey key: String)解决了此问题.由于某种原因,AnyObject不会在Swift 3中转换为Integer,尽管在Swift 2.2中确实如此.

UPDATE: I solved this problem by using decodeInteger(forKey key: String) instead of decodeObject(forKey key: String). By some reason AnyObject does not cast to Integer in Swift 3 though it did in Swift 2.2

推荐答案

当在Swift 2中用NSKeyedArchiver存档的NSData blob在<2在Swift 3中为c4>.我猜是在Swift 2中,BoolInt被编码为NSNumber,但是在Swift 3中,它们被编码为原始BoolInt类型.我相信以下测试支持这一说法:

It appears that this only happens on the Swift 2 to Swift 3 update boundary when a NSData blob archived with a NSKeyedArchiver in Swift 2 is opened with a NSKeyedUnarchiver in Swift 3. My guess is that on Swift 2, the Bool and Int are encoded as NSNumber, but in Swift 3, they are encoded as raw Bool and Int types. I believe the following test supports this claim:

这在Swift 3中可以取消存档在Swift 2中编码的Bool,但是如果Bool是在Swift 3中编码的,则返回nil.

This works in Swift 3 to unarchive a Bool encoded in Swift 2, but returns nil if the Bool was encoded in Swift 3:

let visible = aDecoder.decodeObject(forKey: "visible") as? Bool

这在Swift 3中可以取消存档在Swift 3中编码的Bool,但是如果Bool是在Swift 2中编码的,则崩溃.

This works in Swift 3 to unarchive a Bool encoded in Swift 3, but crashes if the Bool was encoded in Swift 2:

let visible = aDecoder.decodeBool(forKey: "visible")

我的解决方法是:

let visible = aDecoder.decodeObject(forKey: "visible") as? Bool ?? aDecoder.decodeBool(forKey: "visible")

这篇关于NSKeyedArchiver在Swift 3(XCode 8)中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆