快速使用NSData [英] Working with NSData in swift

查看:115
本文介绍了快速使用NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想出了如何快速提取NSData的方法,但是我对设置它感到困惑:

So I've figured out how to extract NSData in swift but i'm getting confused with regards to setting it:

var testBytes : [Byte] = [0x14, 0x00, 0xAB, 0x45, 0x49, 0x1F, 0xEF, 0x15,     
                          0xA8, 0x89, 0x78, 0x0F, 0x09, 0xA9, 0x07, 0xB0,
                          0x01, 0x20, 0x01, 0x4E, 0x38, 0x32, 0x35, 0x56,
                          0x20, 0x20, 0x20, 0x00]

var msgData = NSData(bytes: testBytes, length: testBytes.count)

println("\(msgData)")


var length : Int = testBytes.count

var out: NSInteger = 0

let ptr = UnsafePointer<UInt8>(msgData.bytes)
var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: 28)

所以如果我想访问一个特定的字节,我可以用类似的东西来获取它:

So if i want to access a specific byte I can get it with something like:

let targetAddress = UInt32(bytes[2]) << 16 |
    UInt32(bytes[3]) << 8 |
    UInt32(bytes[4]) << 0

现在说我想用类似这样的值设置一个值:

Now say I wanted to set a value with something like:

bytes[11] = UInt8(UInt32(bytes[11]) | 0x0FF)

我收到错误Cannot assign the result of this expression).我也尝试过使用&bytes[11],它似乎也不飞.

I get an error of Cannot assign the result of this expression). I tried also using &bytes[11] which doesn't seem to fly either.

我假设这是因为数组使用了不安全的缓冲区指针.有一个简单的电话让我知道如何使作业正确完成吗?

I'm assuming this is because the array uses an unsafe buffer pointer. Is there an easy call that I've some how glossed over to make the assignment work correctly?

推荐答案

如果要修改NSData检索的字节 对象,则应将字节复制到单独的数组中

If you want to modify the bytes retrieved from the NSData object, then you should copy the bytes into a separate array

var bytes = [UInt8](count: msgData.length, repeatedValue: 0)
msgData.getBytes(&bytes, length: bytes.count)

bytes[11] = UInt8(UInt32(bytes[11]) | 0x0FF)

NSData是不可变的对象,并且

NSData is an immutable object, and

let ptr = UnsafePointer<UInt8>(msgData.bytes)

是一个常量指针,因此您不得修改指向的数据.

is a constant pointer, so you must not modify the pointed-to data.

或者,从头开始使用 mutable 数据对象:

Alternatively, use a mutable data object from the beginning:

var msgData = NSMutableData(bytes: testBytes, length: testBytes.count)

let ptr = UnsafeMutablePointer<UInt8>(msgData.mutableBytes)
var bytes = UnsafeMutableBufferPointer<UInt8>(start: ptr, count: msgData.length)

bytes[11] = UInt8(UInt32(bytes[11]) | 0x0FF)

请注意msgData.mutableBytes而不是msgData.bytes的用法. 这将直接修改msgData中的数据.

Note the usage of msgData.mutableBytes instead of msgData.bytes. This will modify the data in msgData directly.

这篇关于快速使用NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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