[英]Append bytes to NSInputStream to be read later sequentially
I am getting chunks of NSData
sequentially from server, more than approx. 我从服务器顺序获取
NSData
块,超过约。 4096
bytes at a time, sequentially. 4096
个字节,顺序。 Each received chunk may differ in its size. 每个收到的块的大小可能不同。
What I would like to do, is to append all these bytes somewhere, and at the same time start reading from the beginning of the data, sequentially , 512 bytes at a time maximum. 我想做的是将所有这些字节附加到某处,同时从数据的开头开始读取, 顺序 一次最多512字节 。
While searching I've learned about using NSInputStream
for this, and here is the code snippet: 在搜索时我已经了解了如何使用
NSInputStream
,这里是代码片段:
uint8_t bytes[512];
UInt32 length;
NSInputStream *stream = [[NSInputStream alloc] initWithData:aData];
[stream open];
while (((length = [stream read:bytes maxLength:512]) > 0)) {
if ([self.inputStreamer isKindOfClass:[PLAudioInputStreamerNoOpenClose class]]) {
[self.inputStreamer hasData:bytes length:length];
}
}
While this just works, the initialized NSInputStream
does not seem to allow appending additional bytes after it is initialized, so the only way I could think of is, to initialize NSInputStreams
for every chunk of data, and block until it has reached its end, going on to do the same for next chunk of bytes, as the code above does. 虽然这只是工作,但初始化的
NSInputStream
似乎不允许在初始化之后附加额外的字节,因此我能想到的唯一方法是,为每个数据块初始化NSInputStreams
,并阻塞直到它到达终点,对于下一个字节块执行相同操作,如上面的代码所做的那样。
Is there any more preferred solution for this kind of task? 对于这种任务,还有更优选的解决方案吗? Any help will be appreciated.
任何帮助将不胜感激。 Thank you,
谢谢,
You need a 'read and write' stream. 你需要一个'读写'流。
NSInputStream
is read only and NSOutputStream
is write only. NSInputStream
是只读的, NSOutputStream
是只写的。
If I were you, I just use a NSMutableData and one int variables for 'current reading position'. 如果我是你,我只使用一个NSMutableData和一个int变量作为'当前阅读位置'。
NSMutableData* myData = [[NSMutableData alloc] init];
NSInteger myPos = 0;
[myData appendData:..];
...
// need to check the range (myPos ~ [myData length])
NSData* nextBlockToRead = [NSData dataWithBytesNoCopy:((char*)[myData bytes] + myPos) length:512];
myPos += 512;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.