swift - 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 的初始值无关。任何帮助将不胜感激。谢谢。
解决方案
无需编码 a String
and 或 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)
}
推荐阅读
- swift - iPhone 设备上的画中画模式是否支持使用 swift 进行开发?
- sql-server - 将选择查询的值分配给变量
- php - 来宾和用户 Laravel 的评论表结构
- excel - 优化包含大量“for”和“if”的慢代码
- c - 将变量字符串化的 C 宏
- javascript - React Native Firebase,应用程序在前台时不显示通知,仅在具有捆绑构建的 Android 8 或更高版本上
- node.js - 如何在不获取的情况下获取路由的 json
- angular - 将选定的 ID 从组件传递到另一个组件
- firewall - fail2ban:如果一行匹配failregex 和ignoreregex,哪一个优先?
- javascript - Jquery滚动动画滚动到div的底部而不是顶部