一尘不染

通过NSData对象在Swift中创建一个数组

swift

我正在尝试将整数数组快速存储到磁盘。我可以将它们放到NSData对象中进行存储,但是很难将它们放回到数组中。我可以使用来获取COpaquePointer数据的原始数据,data.bytes但是找不到用该指针初始化新的swift数组的方法。有人知道怎么做吗?

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?

阅读 284

收藏
2020-07-07

共1个答案

一尘不染

您可以使用以下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具有正确值语义的包装器。访问器方法略有不同。

数组到数据:

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]
2020-07-07