来自 UInt8 的 NSData

NSData from UInt8

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

var theData:UInt8!

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

谁能帮我解决 Obj-C 的等效问题?

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

如果你把Swift代码写得稍微简单一点

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

那么将其转换为 Objective-C 就相对简单了:

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

对于多个字节,您将使用数组

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

转换为 Objective-C 为

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

(并且你可以在最后一条语句中省略地址运算符, 参见示例 How come an array's address is equal to its value in C?).

Swift3

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

在Swift,

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

因此,以下将起作用。

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