我正在尝试将整数数组快速存储到磁盘。我可以将它们放到NSData对象中进行存储,但是很难将它们放回到数组中。我可以使用来获取COpaquePointer数据的原始数据,data.bytes但是找不到用该指针初始化新的swift数组的方法。有人知道怎么做吗?
COpaquePointer
data.bytes
import Foundation var arr : UInt32[] = [32,4,123,4,5,2]; let data = NSData(bytes: arr, length: arr.count * sizeof(UInt32)) println(data) //data looks good in the inspector // now get it back into an array?
您可以使用以下getBytes方法NSData:
getBytes
NSData
// the number of elements: let count = data.length / sizeof(UInt32) // create array of appropriate length: var array = [UInt32](count: count, repeatedValue: 0) // copy bytes into array data.getBytes(&array, length:count * sizeof(UInt32)) print(array) // Output: [32, 4, 123, 4, 5, 2]
Swift 3(Xcode 8)的更新: Swift 3具有一个新类型struct Data ,该类型是NS(Mutable)Data具有正确值语义的包装器。访问器方法略有不同。
struct Data
NS(Mutable)Data
数组到数据:
var arr: [UInt32] = [32, 4, UInt32.max] let data = Data(buffer: UnsafeBufferPointer(start: &arr, count: arr.count)) print(data) // <20000000 04000000 ffffffff>
数据到数组:
let arr2 = data.withUnsafeBytes { Array(UnsafeBufferPointer<UInt32>(start: $0, count: data.count/MemoryLayout<UInt32>.stride)) } print(arr2) // [32, 4, 4294967295]
Swift 5更新:
let arr: [UInt32] = [32, 4, UInt32.max] let data = Data(buffer: UnsafeBufferPointer(start: arr, count: arr.count)) print(data) // <20000000 04000000 ffffffff>
var arr2 = Array<UInt32>(repeating: 0, count: data.count/MemoryLayout<UInt32>.stride) _ = arr2.withUnsafeMutableBytes { data.copyBytes(to: $0) } print(arr2) // [32, 4, 4294967295]