What's the best way to implement a Java-like ByteBuffer in Obj-C?
-
21-08-2019 - |
Question
I'm trying to build a application for the iPhone, although I am completely new to Obj-C. For one problem I'd use a ByteBuffer in Java, but I don't see any appropriate class in Apple's documentation. So I probably have to implement it on my own.
My question is, how to do it best:
- Is there a similar class in Obj-C? (That would be the best solution ;))
- Should I do it by using Obj-C classes like NSData?
- Or should I stay with plain C code?
Solution
You probably want NSMutableData.
OTHER TIPS
My recollection of java.nio.ByteBuffer
(from working with Java many moons ago) is that ByteBuffer
implements sequential reads/writes to an array of bytes. This is analogous to an NSInputStream
backed by an NSData
(for input):
NSInputStream *inputStream = [NSInputStream inputStreamwithData:myData]; //assuming myData is NSData*
float myFloat;
if([inputStream hasBytesAvailable]) { // NO if you've already read to the end of myData
NSInteger bytesRead = [inputStream read:&myFloat maxLength:sizeof(myFloat)];
NSAssert(bytesRead == sizeof(myFloat);
}
You can do something similar with an NSOutputStream
writing to an NSData
.
I have a similar question. ilya pointed my here with his answer .
My aim is to implement a fully functional Obj-C version of java.nio.ByteBuffer. Just wanted to know what I should use to get there
That will be your custom class.
For my case I think NSInputStream
and NSOutputStream
should be used. For sure not NSMutableData
as how is the accepted and mostly up voted answer.