首页 > 解决方案 > Swift - 如何使用 NSSecureCoding 对 Bool 类型进行编码

问题描述

我在 Swift 应用程序中使用 NSSecureCoding 保存 Bool 变量时遇到问题。

我对 Objective-C 没有任何经验,而且我对 Swift 比较陌生(我有 ac# 背景)。据我了解,使用 NSSecureCoding 需要我们在 Objective-C 中使用字符串和 int 对应项——即 NSString 和 NSNumber。我能够以这种方式成功地编码和解码整数和字符串:

// 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))")

但这总是打印:Optional(1)与 myBool 的初始值无关。任何帮助将不胜感激。谢谢。

标签: swiftnssecurecoding

解决方案


无需编码 a Stringand 或 a 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)
}

推荐阅读