NSData from UInt8

I recently found the source code in swift, and I'm trying to get it before objective-C. The only thing I could not understand was the following:

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

Can someone help me with the equivalent of Obj-C?

To give you some context, I need to send UInt8 to a CoreBluetooth peripheral device (CBPeripheral) as UInt8. Float or integer will not work because the data type will be too large.

+3
source share
2 answers

If you write Swift code a little easier than

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

it is relatively straightforward to translate this value to Objective-C:

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

For multiple bytes you should use an array

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

which translates to Objective-C as

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

(and you can omit the operator address in the last statement, see for example, Why is the address of the array equal to its value in C? ).

+10
source

In Swift 3

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

Source: https://habr.com/ru/post/1263761/


All Articles