Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

ios - NSData from UInt8

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:

var theData:UInt8!

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

Can anybody help me with the Obj-C equivalent?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you write the Swift code slightly simpler as

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

then it is relatively straight-forward to translate that to 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

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?).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...