xcode 来自 UInt8 的 NSData

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32455543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:47:27  来源:igfitidea点击:

NSData from UInt8

iosobjective-cxcodeswiftnsdata

提问by Ondrej Rafaj

I have recently found a source code in swift and I am trying to get it to objective-C. The one thing I was unable to understand is this:

我最近在 swift 中找到了一个源代码,我正在尝试将其转换为 Objective-C。我无法理解的一件事是:

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. Float or integer won't work because the data type would be too big.

只是为了给你一些上下文,我需要将 UInt8 作为 UInt8 发送到 CoreBluetooth 外围设备 (CBPeripheral)。浮点数或整数将不起作用,因为数据类型太大。

回答by Martin R

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 中的值?)。

回答by YannSteph

In Swift 3

斯威夫特 3

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

回答by AechoLiu

In Swift,

在斯威夫特,

Datahas a native initmethod.

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)