来自UInt8的NSData

时间:2015-09-08 10:36:48

标签: ios objective-c xcode swift nsdata

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

var theData:UInt8!

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

任何人都可以帮我使用Obj-C等同物吗?

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

3 个答案:

答案 0 :(得分:18)

如果你把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)];

(你可以省略最后一个语句中的address-of运算符, 例如,参见How come an array's address is equal to its value in C?)。

答案 1 :(得分:4)

Swift 3

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

答案 2 :(得分:3)

在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)