在Swift应用程序中使用NSSecureCoding保存Bool变量时遇到问题。
我没有任何使用Objective-C的经验,而且我对Swift比较陌生(我有c#背景)。据我所知,使用NSSecureCoding要求我们使用Objective-C中的string和int对应物,即NSString和NSNumber。我能够以这种方式成功地编码和解码int和string:
// Encode
coder.encode(myString as NSString, forKey: PropertyKey.myStrKey)
coder.encode(NSNumber(value: myInt), forKey: PropertyKey.myIntKey)
// Decode
let myString = coder.decodeObject(of: NSString.self, forKey: PropertyKey.myStrKey) as String? ?? ""
let myInt = coder.decodeObject(of: NSNumber.self, forKey: PropertyKey.myIntKey)然而,我不确定如何处理布尔值。我试过这个:
// Encode
coder.encode(NSNumber(value: myBool), forKey: PropertyKey.myBoolKey)
// Decode
let myBool = coder.decodeObject(of: NSNumber.self, forKey: PropertyKey.myBoolKey)
print("\(String(describing: myBool))")但是,无论myBool的初始值是什么,都会输出:Optional(1)。任何帮助都将不胜感激。谢谢。
发布于 2021-02-16 09:03:00
无需对String和/或NSNumber进行编码。您可以简单地对您的Bool进行编码,只需确保在解码时使用NSCoder的decodeBool方法。
游乐场测试:
class Test: NSObject, NSSecureCoding {
static var supportsSecureCoding: Bool = true
var aBool: Bool
required init(aBool: Bool) {
self.aBool = aBool
}
func encode(with coder: NSCoder) {
coder.encode(aBool, forKey: "aBool")
}
required init?(coder: NSCoder) {
aBool = coder.decodeBool(forKey: "aBool")
}
}let test = Test(aBool: true)
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: test, requiringSecureCoding: true)
print("data size:", data.count) // data size: 251
let decoded = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! Test
print("aBool", decoded.aBool) // aBool true
} catch {
print(error)
}https://stackoverflow.com/questions/66217300
复制相似问题