如何将NSTimeInterval
值转换为NSData
?
答案 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