微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift - 如何使用 NSSecureCoding 对 Bool 类型进行编码

如何解决Swift - 如何使用 NSSecureCoding 对 Bool 类型进行编码

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

我对 Objective-C 没有任何经验,而且我对 Swift 比较陌生(我有 C# 背景)。据我了解,使用 NSSecureCoding 需要我们在 Objective-C 中使用 string 和 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 的初始值如何。 任何帮助将不胜感激。谢谢。

解决方法

无需对 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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。