ios - 如何将 bool 转换为 NSData

标签 ios swift nsdata nskeyedunarchiver

我找到了 this postInt 转换为 NSData

它说要这样做:

var foo: Int = 1000
let data = NSData(bytes: &foo, length: sizeof(Int))

我在想,我是否应该像这样将 Bool 转换为 NSData,像这样:

 var purchase: Bool = true
 let data = NSData(bytes: &purchase, length: sizeof(Bool))

在我的例子中,我总是知道 Bool 为真。既然如此,我想知道是否有更简单的方法将值“true”转换为 NSData 对象。

一些背景语境:

我将此 NSData 值存储在带有 this library 的钥匙串(keychain)中.

我还将使用 NSKeyedUnarchiver.unarchiveObjectWithDataNSData 值转换回 bool 值

最佳答案

Swift >= 4 解

我们可以使用 JSONEncoder 轻松实现这一点,因为 Bool struct 确认 Codable Typealias

let mBoolValue = true
let boolData = try! JSONEncoder().encode(mBoolValue)

关于ios - 如何将 bool 转换为 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509951/

相关文章:

ios - 如何在 iOS 上读取-修改-写入 PDF (CGPDFDocument)?

javascript - 如何使用firebase云函数从firebase数据库检索子节点的键值?

ios - swift : How to save latitude and longitude to use in another swift file

iphone - #error 1107 在 iPhone 上运行 flash 游戏时,使用 Adob​​e Air

ios - 将所选图像放入网格

ios - 使用 NSURLConnection 渐进式 JPG 下载

swift - 在 Swift 中将 UnsafeMutableBufferPointer<Bit> 转换为 NSData

ios - 在 Objective-C 中读取 gzip 压缩字符串失败?

iOS通知-对象参数可以是任意对象吗?

ios - 在 swift iOS 应用程序中使用 FBSDK 的问题