将NSTimeInterval转换为NSData并返回NSTimeInterval

时间:2015-11-11 14:56:11

标签: swift nsdata nstimeinterval

如何将NSTimeInterval值转换为NSData

3 个答案:

答案 0 :(得分:4)

Xcode 8.3.1•Swift 3.1

var nowInterval = Date().timeIntervalSince1970                                  // 1491800604.362141
let data = Data(bytes: &nowInterval, count: MemoryLayout<TimeInterval>.size)    // 8 bytes
let timeInterval: Double = data.withUnsafeBytes{ $0.pointee }

let date = Date(timeIntervalSince1970: timeInterval)   // Apr 10, 2017, 2:03 AM"

答案 1 :(得分:3)

NSTimeInterval只是Double的一种类型。您可以通过复制字节来存档它,就像使用任何其他Foundation类型一样。

var time = NSTimeInterval(100) // 100.0

let timeData = NSData(bytes: &time, length: sizeof(NSTimeInterval))

var unarchivedTime = NSTimeInterval() // You need to initialize an empty NSTimeInterval object as a var in order to mutate it

timeData.getBytes(&unarchivedTime, length: sizeof(NSTimeInterval))

print(unarchivedTime) // 100.0

答案 2 :(得分:3)

您也可以使用NSKeyedArchiver

&i32