我最近在 swift 中找到了一个源代码,我正试图将其转换为 objective-C。我无法理解的一件事是:
var theData:UInt8!
theData = 3;
NSData(bytes: [theData] as [UInt8], length: 1)
谁能帮我解决 Obj-C 的等效问题?
只是为了给你一些上下文,我需要将 UInt8 作为 UInt8 发送到 CoreBluetooth 外围设备 (CBPeripheral)。 float 或整数将不起作用,因为数据类型太大。
最佳答案
如果你写的 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? ).
关于ios - 来自 UInt8 的 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32455543/