简体   繁体   English

来自 UInt8 的 NSData

[英]NSData from UInt8

I have recently found a source code in swift and I am trying to get it to objective-C.我最近在 swift 中找到了一个源代码,我正在尝试将其转换为 Objective-C。 The one thing I was unable to understand is this:我无法理解的一件事是:

var theData:UInt8!

theData = 3;
NSData(bytes: [theData] as [UInt8], length: 1)

Can anybody help me with the Obj-C equivalent?任何人都可以帮助我使用 Obj-C 等效项吗?

Just to give you some context, I need to send UInt8 to a CoreBluetooth peripheral (CBPeripheral) as UInt8.只是为了给你一些上下文,我需要将 UInt8 作为 UInt8 发送到 CoreBluetooth 外围设备 (CBPeripheral)。 Float or integer won't work because the data type would be too big.浮点数或整数将不起作用,因为数据类型太大。

If you write the Swift code slightly simpler as如果你写的 Swift 代码稍微简单一点

var theData : UInt8 = 3
let data = NSData(bytes: &theData, length: 1)

then it is relatively straight-forward to translate that to Objective-C:那么将其转换为 Objective-C 相对简单:

uint8_t theData = 3;
NSData *data = [NSData dataWithBytes:&theData length:1];

For multiple bytes you would use an array对于多个字节,您将使用数组

var theData : [UInt8] = [ 3, 4, 5 ]
let data = NSData(bytes: &theData, length: theData.count)

which translates to Objective-C as转换为 Objective-C 为

uint8_t theData[] = { 3, 4, 5 };
NSData *data = [NSData dataWithBytes:&theData length:sizeof(theData)];

(and you can omit the address-of operator in the last statement, see for example How come an array's address is equal to its value in C? ). (并且您可以省略最后一条语句中的 address-of 运算符,例如参见数组的地址如何等于其在 C 中的值? )。

In Swift 3斯威夫特 3

var myValue: UInt8 = 3 // This can't be let properties
let value = Data(bytes: &myValue, count: MemoryLayout<UInt8>.size)

In Swift,在斯威夫特,

Data has a native init method. Data有一个原生的init方法。

// Foundation -> Data  

/// Creates a new instance of a collection containing the elements of a
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
///   `elements` must be finite.
@inlinable public init<S>(_ elements: S) where S : Sequence, S.Element == UInt8

@available(swift 4.2)
@available(swift, deprecated: 5, message: "use `init(_:)` instead")
public init<S>(bytes elements: S) where S : Sequence, S.Element == UInt8

So, the following will work.因此,以下将起作用。

let values: [UInt8] = [1, 2, 3, 4]
let data = Data(values)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM