I am getting chunks of NSData
sequentially from server, more than approx. 4096
bytes at a time, sequentially. 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.
While searching I've learned about using NSInputStream
for this, and here is the code snippet:
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.
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.
If I were you, I just use a NSMutableData and one int variables for 'current reading position'.
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;