简体   繁体   English

在 Obj-C 中实现类似 Java 的 ByteBuffer 的最佳方法是什么?

[英]What's the best way to implement a Java-like ByteBuffer in Obj-C?

I'm trying to build a application for the iPhone, although I am completely new to Obj-C.我正在尝试为 iPhone 构建一个应用程序,尽管我对 Obj-C 完全陌生。 For one problem I'd use a ByteBuffer in Java, but I don't see any appropriate class in Apple's documentation.对于一个问题,我会在 Java 中使用 ByteBuffer,但我在 Apple 的文档中没有看到任何合适的 class。 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? Obj-C中是否有类似的class? (That would be the best solution;)) (那将是最好的解决方案;))
  • Should I do it by using Obj-C classes like NSData?我应该使用像 NSData 这样的 Obj-C 类吗?
  • Or should I stay with plain C code?还是我应该使用普通的 C 代码?

You probably want NSMutableData.你可能想要 NSMutableData。

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.我对java.nio.ByteBuffer的回忆(许多个月前与 Java 合作)是ByteBuffer实现了对字节数组的顺序读/写。 This is analogous to an NSInputStream backed by an NSData (for input):这类似于由NSData支持的NSInputStream (用于输入):

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 .您可以通过将NSOutputStream写入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.我的目标是实现一个功能齐全的 Obj-C 版本的 java.nio.ByteBuffer。 Just wanted to know what I should use to get there只是想知道我应该用什么来到达那里

That will be your custom class.那将是您的自定义 class。

For my case I think NSInputStream and NSOutputStream should be used.就我而言,我认为应该使用NSInputStreamNSOutputStream For sure not NSMutableData as how is the accepted and mostly up voted answer.肯定不是NSMutableData是如何被接受且大多数人投票赞成的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM