我正在使用ARKit和GameKitMatches,所以我不能使用Codable(据我所知),因为MCPeerID和ARWorldMap都不是可编码的,首先要解决这个问题。
所以我使用NSCoding和NSSecureCoding,但出现了错误:
The data couldn’t be read because it isn’t in the correct format.
即使我刚刚创建了它。
我还尝试使用NSKeyedUnarchiver.unarchivedObject(ofClasses: classes
,但在我的init中抛出了意外的nil。
下面是我制作的一个playground,展示了这个问题:
class CodingData: NSObject, NSCoding, NSSecureCoding {
static var supportsSecureCoding = true
var dic: [String: Int]!
var i: Int!
func encode(with coder: NSCoder) {
coder.encode(i, forKey: "i")
coder.encode(dic, forKey: "dic")
}
required convenience init?(coder: NSCoder) {
let anInt = coder.decodeObject(forKey: "i") as! Int
let anDic = coder.decodeObject(forKey: "dic") as! [String: Int]
self.init(dic: anDic, i: anInt)
}
init(dic: [String: Int], i: Int){
self.dic = dic
self.i = i
}
}
do{
let test = CodingData(dic: [:], i: 0)
//let classes = [NSDictionary.self, NSNumber.self]
let testData = try NSKeyedArchiver.archivedData(withRootObject: test, requiringSecureCoding: true)
let emptyDic = try NSKeyedUnarchiver.unarchivedObject(ofClass: CodingData.self, from: testData)
// Error here ^^^^^^
}catch{
error.localizedDescription
}
顺便说一下,不确定是否重要,但在尝试调试init中的coder
时,它总是显示(可能只是一个错误):
error: <EXPR>:1:1: error: non-nominal type '$__lldb_context' (aka 'Self') cannot be extended
extension $__lldb_context {
^ ~~~~~~~~~~~~~~~
error: <EXPR>:19:27: error: value of type 'Self' has no member '$__lldb_wrapped_expr_28'
$__lldb_injected_self.$__lldb_wrapped_expr_28(
~~~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~