views:

453

answers:

2

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?
+6  A: 

You probably want NSMutableData.

Mark Probst
+1 - that would be it.
Eric Petroelje
Ok... do you have any example how to read a e.g. a float from NSMutableData? Or any other data type?
Koraktor
AFAIK there are no such methods, but you can implement them yourself as a category of NSData, so they're usable with NSData and any of its subclasses. Just use getBytes:length: to fetch sizeof(float) bytes and then cast the buffer.
Mark Probst
+3  A: 

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.

Barry Wark
This looks pretty promising. Thank you very much.
Koraktor
I'm curious to see how your port turns out and would be very interested in using the result. Please ping me when it's ready.
Barry Wark
I'll try to remember. ;)
Koraktor
I'm done with a working Obj-C version of ByteBuffer. You can have a look at it here:http://github.com/koraktor/steam-condenser/blob/objc/objc/src/ByteBuffer.h,http://github.com/koraktor/steam-condenser/blob/objc/objc/src/ByteBuffer.m
Koraktor
The github.com links are broken, but I'm very excited to take a look when the code is back up.
Barry Wark
Oh I'm sorry. I had to delete the branch again as it contained some things I didn't want to be online at the moment. But I forget to push the up to GitHub again.They're online now.
Koraktor