从NSData对象创建斯威夫特数组 [英] Create an Array in Swift from an NSData Object

查看:167
本文介绍了从NSData对象创建斯威夫特数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图整数数组存储在磁盘中迅速。我可以让他们到一个NSData对象来存储,但让他们背出到一个数组是困难的。我能得到一个原始的 COpaquePointer data.bytes 中的数据,但无法找到一个方法来初始化新迅速阵列的指针。有谁知道该怎么办呢?

 进口基金会VAR ARR:UInt32的[] = [32,4,123,4,5,2];让数据= NSData的(字节数:ARR,长度:arr.count *的sizeof(UInt32的))的println(数据)//数据看起来在检查好//现在拿回来到一个数组?


解决方案

您可以使用的的getBytes 方法的NSData

  //元素的个数:
让数= data.length /的sizeof(UInt32的)//创建适当长度的数组:
VAR阵列= [UInt32的](计数:算,repeatedValue:0)//复制字节到数组
data.getBytes(安培;数组长度:计数*的sizeof(UInt32的))打印(阵列)
//输出:[32,4,123,4,5,2]

I'm trying to store an array of integers to disk in swift. I can get them into an NSData object to store, but getting them back out into an array is difficult. I can get a raw COpaquePointer to the data with data.bytes but can't find a way to initialize a new swift array with that pointer. Does anyone know how to do it?

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?

解决方案

You can use the getBytes method of 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]

这篇关于从NSData对象创建斯威夫特数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆